node.js 快递路线参数条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11258442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:56:16  来源:igfitidea点击:

Express routes parameter conditions

node.jsexpressroutingurl-routing

提问by danmactough

I have a route on my Express app that looks like this:

我的 Express 应用程序上有一条路线,如下所示:

app.get('/:id', function (request, response) {
  …
});

The ID will always be a number. However, at the moment this route is matching other things, such as /login.

ID 将始终是一个数字。但是,目前这条路线正在匹配其他东西,例如/login.

I think I want two things from this:

我想我想从中得到两件事:

  1. to only use this route if the ID is a number, and
  2. only if there isn't a route for that specific paramater already defined (such as the clash with /login).
  1. 如果 ID 是数字,则仅使用此路由,并且
  2. 仅当尚未定义该特定参数的路由时(例如与 发生冲突/login)。

Can this be done?

这能做到吗?

回答by danmactough

Expanding on Marius's answer, you can provide the regex AND the parameter name:

扩展 Marius 的答案,您可以提供正则表达式和参数名称:

app.get('/:id(\d+)/', function (req, res){
  // req.params.id is now defined here for you
});

回答by Marius Kjeldahl

Yes, check out http://expressjs.com/guide/routing.htmland https://www.npmjs.com/package/path-to-regexp(which express uses). An untested version that may work is:

是的,请查看http://expressjs.com/guide/routing.htmlhttps://www.npmjs.com/package/path-to-regexp(express使用)。可能有效的未经测试的版本是:

app.get(/^(\d+)$/, function (request, response) {
  var id = request.params[0];
  ...
});

回答by Marco Godínez

You can use:

您可以使用:

// /12345
app.get(/\/([^\/]+)\/?/, function(req, res){
  var id = req.params[0];
  // do something
});

or this:

或这个:

// /post/12345
app.get(/\/post\/([^\/]+)\/?/, function(req, res){
  var id = req.params[0];
  // do something
});