ExpressJS request body is empty if i don't use multer

Issue

I have this very strange issue with my express app, i simply want to access req.body data that are send through post request via form-data but unfortunately i get undefined error when i try to access those values in request.body but what is strange about this is if i use multer middleware (i used this on another route to upload files) i don’t get this error.
i have configured default body parser provided by express.

//body pharser
app.use(express.json());
app.use(
  express.urlencoded({
    extended: true,
  })
);

//multer configuration
const ImageUpload = multer({
  storage: storage,
  limits: { fileSize: 4194304 },
  fileFilter: Imagfilter,
});

//this will return undefined
app.post("/available",(req, res) => {
  console.log(req.body.name);
}

//but this will return the value without any issues
app.post(
  "/available",
  ImageUpload.fields([
    { name: "nicImageFront", maxCount: 1 },
    { name: "nicImageBack", maxCount: 1 },
  ]),
  (req, res) => {
 console.log(req.body.name);
}

Solution

There’s nothing strange about that.

FormData objects generate multipart requests. They have to, it is how they support file uploads.

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".

Multer is designed to parse multipart requests.

The urlencoded middleware is designed to parse urlencoded requests, not multipart requests.

The json middleware is designed to parse JSON encoded requests, not multipart requests.

Answered By – Quentin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published