我尝试在 router.use
中向 router.post
和 router.get
公开我的表单验证脚本。我使用 req.body.value
从输入字段获取数据。这在 router.post
中有效,但在 router.use
中无效。对于此代码,我收到以下错误消息(TypeError:无法读取未定义的属性“长度”
):
router.use('/', (req, res, next) => {
if(req.body.firstname.length === 0 || !req.body.firstname.match(/\D+/igm)) {
var validateFirstname = false;
} else {
var validateFirstname = true;
};
if(validateFirstname === true) {
console.log('SUCCESS: Form validated!');
} else {
console.log('ERROR: Form not validated!');
};
next();
});
谁能给我解释一下这是为什么?有没有办法将这个if else
语句实现到router.use
中?稍后,当在 router.get
中验证表单时,这将有助于将 html div 发送回用户。
更新:
我的验证问题是在加载后表单为空时检查表单,这就是返回 undefined
的原因。但是 req.body
在填充数据时在 router.use
中没有问题。有没有办法检查除页面加载之外的输入字段?
最佳答案
我建议使用 express-validator 作为一个很好的替代方案,你如何组织验证?模块。
示例
var util = require('util'),
express = require('express'),
expressValidator = require('express-validator'),
app = express.createServer();
app.use(express.bodyParser());
// this line must be immediately after express.bodyParser()!
app.use(expressValidator([options]));
app.post('/:urlparam', function(req, res) {
// VALIDATION
// checkBody only checks req.body; none of the other req parameters
// Similarly checkParams only checks in req.params (URL params) and
// checkQuery only checks req.query (GET params).
req.checkBody('postparam', 'Invalid postparam').notEmpty().isInt();
req.checkParams('urlparam', 'Invalid urlparam').isAlpha();
req.checkQuery('getparam', 'Invalid getparam').isInt();
...
var errors = req.validationErrors();
...
});
关于javascript - Express:为什么不能在router.use中使用req.body.value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37368357/