发生的情况是:当您在验证链中使用消毒剂时,它们仅在验证期间应用。
如果您想保留已清理的值,则应使用以下 sanitize 函数express-validator/filter
:
app.post('/some/path', [
check('user_name').isLength({ min: 1 }).trim().withMessage('User name is required.'),
sanitize('user_name').trim()
], function (req, res) {
// your sanitized user_name here
let user_name = req.body.user_name
});
如果您想始终修剪所有请求正文而不清理每个字段,您可以使用trim-request模块,这是一个示例:
const { check, validationResult } = require('express-validator/check');
const trimRequest = require('trim-request');
app.post('/some/path', trimRequest.body, [
check('user_name').isLength({ min: 1 }).trim().withMessage('User name is required.'),
], function (req, res) {
// your sanitized user_name here
let user_name = req.body.user_name
});