简体   繁体   English

如果我不使用 multer,ExpressJS 请求正文为空

[英]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.我的 express 应用程序有这个非常奇怪的问题,我只是想访问通过表单数据通过 post 请求发送的 req.body 数据,但不幸的是,当我尝试访问 request.body 中的这些值时出现未定义的错误,但什么是奇怪的是,如果我使用 multer 中间件(我在另一条路线上使用它来上传文件)我没有收到此错误。 i have configured default body parser provided by express.我已经配置了 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. FormData对象生成多部分请求。 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. FormData 接口提供了一种方法来轻松构造一组表示表单字段及其值的键/值对,然后可以使用 XMLHttpRequest.send() 方法轻松发送。 It uses the same format a form would use if the encoding type were set to "multipart/form-data".如果编码类型设置为“multipart/form-data”,它使用与表单相同的格式。

Multer is designed to parse multipart requests. Multer 旨在解析多部分请求。

The urlencoded middleware is designed to parse urlencoded requests, not multipart requests. urlencoded中间件旨在解析 urlencoded 请求,而不是多部分请求。

The json middleware is designed to parse JSON encoded requests, not multipart requests. json中间件旨在解析 JSON 编码请求,而不是多部分请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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