我是node.js / express.js新手。如何验证:id
参数?我想只将数字传递给:id
个参数。如果:id
是一个字符串或包含其中一个字符串,我会显示404错误,例如zend框架路由http://framework.zend.com/manual/current/en/user-guide/routing-and-controllers.html
/routes/users.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/:id?/', function(req, res, next) {
var id = req.params.id;
if(id){
res.render('single-users', { title: 'Single ' + id });
}else {
res.render('users', { title: 'All users' });
}
});
module.exports = router;
我试图改变
router.get('/:id?/', function(req, res, next)
到
router.get('/[0-9]+?/', function(req, res, next)
但是
localhost:3000/users/ab/
工作并显示single-users
页面,我想要它..
LUCAS COSTA建议的解决方案
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/:id(\\d+)?/', function(req, res) {
var id = req.params.id;
if(id){
res.render('single-users', { title: 'Single ' + id });
}else {
res.render('users', { title: 'All users' });
}
});
module.exports = router;
或
router.get('/:id([0-9]+)?/', function(req, res)
答案 0 :(得分:4)
答案 1 :(得分:3)
为什么不在主代码块内部进行仅整数检查,然后有条件地返回404呢?
router.get('/:id', function(req, res, next) {
var id = req.params.id;
if(id && string.match(/^[0-9]+$/) != null)}
res.render('single-users', { title: 'Single ' + id });
}else if(string.match(/^[0-9]+$/) == null){
res.status(404).render('your-404-view');
}else{
res.render('users', { title: 'All users' });
}
});