简体   繁体   中英

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

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM