multer 中间件无法识别请求体
multer middleware does not recognize body of req
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "public/images");
},
filename: (req, file, cb) => {
console.log(req.body); // <- This will output null object
cb(null, file.originalname);
},
});
const upload = multer({ storage });
app.post("/api/upload", upload.single("file"), (req, res) => {
try {
return res.status(200).json(req.body);
} catch (err) {
console.log(err);
}
});
邮递员要求:
控制台输出:
>>>>>>>>>>>>>SERVER STARTED<<<<<<<<<<<<<
(node:3741192) [MONGODB DRIVER] Warning: Top-level use of w, wtimeout, j, and fsync is deprecated. Use writeConcern instead.
(node:3741192) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
Connected to MongoDB
[Object: null prototype] {}
::1 - - [08/Jun/2021:12:11:21 +0000] "POST /api/upload HTTP/1.1" 200 23
我的问题是:
filename: (req, file, cb) => {
console.log(req.body); // <- This will output null object
cb(null, file.originalname);
},
req.body
是一个空对象。但它不应该?在邮递员请求中,我包含了一个 name
属性.
Note that req.body might not have been fully populated yet. It depends
on the order that the client transmits fields and files to the server.
因此,更改邮递员表格中的顺序并将 name
放在 file
之前(您可以简单地 drag/drop 该行)将解决问题。
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "public/images");
},
filename: (req, file, cb) => {
console.log(req.body); // <- This will output null object
cb(null, file.originalname);
},
});
const upload = multer({ storage });
app.post("/api/upload", upload.single("file"), (req, res) => {
try {
return res.status(200).json(req.body);
} catch (err) {
console.log(err);
}
});
邮递员要求:
控制台输出:
>>>>>>>>>>>>>SERVER STARTED<<<<<<<<<<<<<
(node:3741192) [MONGODB DRIVER] Warning: Top-level use of w, wtimeout, j, and fsync is deprecated. Use writeConcern instead.
(node:3741192) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
Connected to MongoDB
[Object: null prototype] {}
::1 - - [08/Jun/2021:12:11:21 +0000] "POST /api/upload HTTP/1.1" 200 23
我的问题是:
filename: (req, file, cb) => {
console.log(req.body); // <- This will output null object
cb(null, file.originalname);
},
req.body
是一个空对象。但它不应该?在邮递员请求中,我包含了一个 name
属性.
Note that req.body might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server.
因此,更改邮递员表格中的顺序并将 name
放在 file
之前(您可以简单地 drag/drop 该行)将解决问题。