Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

463
Vistas
How to upload Image with json using Nodejs

I'm trying to upload an image with a body of json data. I've seen how to do the request in postman, but in my terminal, I get the following when consolelogging the req.body

[Object: null prototype] { '': '"product": "pokemon"' } when loging req.body.product returns as undefined

The image was uploaded successfully, and new product was created, but with no json data. When sending the request just with body and no image, then it is also working. How can I make them work together?

Here is my code:

export const addNewProduct = async (req, res, next) => {
  const userId = req.params.userId;
  const user = await User.findById(userId);
  if (!user) {
    return next(createError(404, "User with id"+ ${userId} +"not found"));
  }

  try {
    let result;
    if (req.file !== undefined && req.file.path !== undefined) {
      result = await cloudinary.v2.uploader.upload(req.file.path, {
        folder: `capstone/products/${userId}`,
      });
    }

    console.log(req.body);

    const newProductData = {
      // product: req.body.product,
      // amount: req.body?.amount || "",
      // untis: req.body?.units || "",
      // price: req.body?.price || "",
      ...req.body,
      businessId: userId,
      image:
        result?.url ||
        req.body?.image ||
        "https://via.placeholder.com/300/09f/fff.png",
      cloudinary_id: result?.public_id || "",
    };
    const newProduct = new Product(newProductData);
    const createdProduct = await newProduct.save();

    res.status(200).send(createdProduct);
  } catch (error) {
    if (error.name === "ValidationError") {
      next(createError(400, error));
    } else {
      next(createError(500, error));
    }
  }
};

I want to use the same endpoint as I am creating a new "product", and want the option of uploading an image with its details when created. The URL from Cloudinary is then stored in the product.

Example of json:

{ "product": "toy", "price": "1.99", "amount": "1", "status": "high"} only product is a required string in model. *doing a middleware check to see if it is unique.

in postman I did use the auto, application/json , multipart/form-data etc. I also added on seperate occasions "data" or "json"in the key pair

Postman on auto content tyoe

example of postman with content type added

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I've managed to solve it with the following: POSTMAN solution

And in the front-end, I had to append all objects, not just the image when an image was sent. thus all under formdata. and a if statement without the image file attached, sending it as normal JSON. Thanks for all's input- learnt a lot along the way.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda