(Express js 4 Multer) 在文件上传前检查表单字段(如果为空)

(Express js 4 Multer) check form fields (if empty) before file upload

我要检查表单字段是否为空,以及在上传文件之前是否更改了名称,但 multer 首先上传文件然后 req.body 被填充。我正在使用 multer 作为中间件。

Upload.js

checkField: function(req, res, next) {
   //Here i want to check if req.body.field1, field2 are empty or not
   //If empty res.send('Required fields are empty');
   console.log(req.body); //This returns empty {}
},
module.exports = {
uploadFile: multer({
    limits: {
        files: 1
    },
    dest: '/upload/',
})
};

路由器:

app.post('/upload', upload.checkField, upload.uploadFile, function(req, res){});

如果您的目标是检查请求中发送的内容,则中间件顺序错误。在解析之前,您无法查看已解析的请求体。试试这个顺序:

app.post('/upload', upload.uploadFile, upload.checkField, function(req, res){});