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