Node.js - Express.js URL参数验证

时间:2016-03-16 17:53:32

标签: javascript node.js express

我是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)

2 个答案:

答案 0 :(得分:4)

您可以提供正则表达式:

router.get('/:id(\\d+)/', function (req, res, next){
    // body
});

Docs

答案 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' });
  }
});