0

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

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
  • What json data? – evolutionxbox Dec 08 '21 at 10:59
  • { "product": "toy", "price": "1.99", "amount": "1", "status": "high"} example of json body. I updated it with images in question - postman . – FlyingVespa Dec 08 '21 at 11:17
  • application/json is a text based format. It cannot be used to send binary. multipart/form-data is the correct type for file upload, but you lose automatic json conversion on the request handler as all data is marked as binary. You need to manually extract the json part of the payload and `JSON.parse()` it. If you are using express, it's a duplicate of https://stackoverflow.com/questions/40076807/node-expressjs-parsing-a-multipart-form-data-post-data-using-body-parser-middl – Alex Blex Dec 08 '21 at 18:51

1 Answers1

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.