I'm building a crud application using mern stack which allows the user to use a form to upload images and input other pieces of data such as product name, description, quantity and price. When testing the api endpoint in postman I get this error.
MulterError: Unexpected field
at wrappedFileFilter (C:\React Applications\Nifet Health\node_modules\multer\index.js:40:19)
at Multipart.<anonymous> (C:\React Applications\Nifet Health\node_modules\multer\lib\make-middleware.js:107:7)
at Multipart.emit (node:events:520:28)
at HeaderParser.cb (C:\React Applications\Nifet Health\node_modules\busboy\lib\types\multipart.js:358:14)
at HeaderParser.push (C:\React Applications\Nifet Health\node_modules\busboy\lib\types\multipart.js:162:20)
at SBMH.ssCb [as _cb] (C:\React Applications\Nifet Health\node_modules\busboy\lib\types\multipart.js:394:37)
at feed (C:\React Applications\Nifet Health\node_modules\streamsearch\lib\sbmh.js:248:10)
at SBMH.push (C:\React Applications\Nifet Health\node_modules\streamsearch\lib\sbmh.js:104:16)
at Multipart._write (C:\React Applications\Nifet Health\node_modules\busboy\lib\types\multipart.js:567:19)
at writeOrBuffer (node:internal/streams/writable:389:12)
/ @desc Create product
// @route POST /api/products
// @access Private
const createProduct = asyncHandler(upload.single('image'), async(req, res) => {
if(!req.body.name || !req.body.price || !req.body.quantity || !req.body.description){
throw new Error('Please add all fields')
}
// Upload image to cloudinary
const result = await cloudinary.uploader.upload(req.file.path);
// Create new product
const product = await Product.create({
name: req.body.name,
price: req.body.price,
quantity: req.body.quantity,
description: req.body.description,
cloudinary_id: result.public_id
})
res.status(200).json(result)
})
multer file
const multer = require("multer");
const path = require("path");
// Multer config
module.exports = multer({
storage: multer.diskStorage({}),
fileFilter: (req, file, cb) => {
let ext = path.extname(file.originalname);
if (ext !== ".jpg" && ext !== ".jpeg" && ext !== ".png") {
cb(new Error("File type is not supported"), false);
return;
}
cb(null, true);
},
});
CodePudding user response:
In your request the field name for the file is missing. It must match the string you set in upload.single('<fieldName>')
.
So in your postman-example set image
as the name for your file.
It also mentioned in the docs:
It is important that you use the name field value from the form in your upload function. This tells multer which field on the request it should look for the files in. If these fields aren't the same in the HTML form and on your server, your upload will fail