我使用express for node.js得到了我的param的冒号

Gen*_*uro 2 rest routing node.js express

这是我的路线:

router.route('/search:word').get(function(req, res) {
  var re = new RegExp(req.params.word, 'i');
  console.log(req.params.word);

  Place.find().or([{ 'title': { $regex: re }}, { 'category': { $regex: re }}]).sort('title').exec(function(err, places) {
    res.json(JSON.stringify(places));
  });
});
Run Code Online (Sandbox Code Playgroud)

当我使用请求时/places/search:test,控制台显示:test而不是"test".知道发生了什么事吗?

Ben*_*Ben 15

你真的想用router.route('/search:word')而不是router.route('/search/:word')吗?使用冒号似乎有点奇怪.

如果您使用router.route('/search/:word'),如果您的请求是

/places/search/test

然后你得到 req.params.word="test"


Jai*_*Ram 5

如果您想要相同模式的 api 端点,例如: /places/search:test那么在 api 端点中,您必须使用双冒号。例子 -

router.route('/search::word').get(function(req, res) {
   console.log(req.params.word); ---> "test"
});
Run Code Online (Sandbox Code Playgroud)

这就是为什么你会得到额外的冒号 :test