express-validator 在使用 form-data 时无法计算 body 字段
express-validator can't evaluate body fields when form-data is used
我正在尝试将 express-validator 与 multer 结合使用来验证 POST 请求的 body 组件,该请求还包含图像、headers 和参数.我已经尝试使用 body() 样式验证方法和 checkSchema 样式,但都不能正确验证我的 body 文本字段。
出于某种原因,checkSchema 样式将适用于我的 headers 和参数,但不适用于 body。
也许我需要重新安排一下?
const express = require('express');
const multer = require('multer');
const { checkSchema } = require('express-validator');
const router = express.Router();
const upload = multer();
// inputs coming in from everywhere - header, params and form-data
router.post(
'/:aId/help/:tId/blah',
checkSchema({
aId: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// this check works!
in: ['params'],
errorMessage: 'aId is wrong',
isAscii: true
},
tId: {
// this check works
in: ['headers'],
errorMessage: 'pId is wrong',
isAscii: true
},
uploadedTime: {
// these checks fail to work
in: ['body'],
errorMessage: 'uploadedTime is wrong',
isInt: true
},
uploadedByName: {
// these checks fail to work
in: ['body'],
errorMessage: 'uploadedByName is wrong',
isInt: false
}
}),
upload.single('file'),
async (req, res) => {
console.log('ANY REQ params?', req.params);
console.log('ANY headers?', req.headers);
console.log('ANY BODY?', req.body);
console.log('ANY FILES?', req.file);
}
);
我的日志显示 body:
ANY BODY? [Object: null prototype] {
uploadedTime: '1646762107739',
uploadedByName: 'Moe S'
}
multer 用法需要在验证之前进行
我正在尝试将 express-validator 与 multer 结合使用来验证 POST 请求的 body 组件,该请求还包含图像、headers 和参数.我已经尝试使用 body() 样式验证方法和 checkSchema 样式,但都不能正确验证我的 body 文本字段。 出于某种原因,checkSchema 样式将适用于我的 headers 和参数,但不适用于 body。 也许我需要重新安排一下?
const express = require('express');
const multer = require('multer');
const { checkSchema } = require('express-validator');
const router = express.Router();
const upload = multer();
// inputs coming in from everywhere - header, params and form-data
router.post(
'/:aId/help/:tId/blah',
checkSchema({
aId: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// this check works!
in: ['params'],
errorMessage: 'aId is wrong',
isAscii: true
},
tId: {
// this check works
in: ['headers'],
errorMessage: 'pId is wrong',
isAscii: true
},
uploadedTime: {
// these checks fail to work
in: ['body'],
errorMessage: 'uploadedTime is wrong',
isInt: true
},
uploadedByName: {
// these checks fail to work
in: ['body'],
errorMessage: 'uploadedByName is wrong',
isInt: false
}
}),
upload.single('file'),
async (req, res) => {
console.log('ANY REQ params?', req.params);
console.log('ANY headers?', req.headers);
console.log('ANY BODY?', req.body);
console.log('ANY FILES?', req.file);
}
);
我的日志显示 body:
ANY BODY? [Object: null prototype] {
uploadedTime: '1646762107739',
uploadedByName: 'Moe S'
}
multer 用法需要在验证之前进行