javascript Express 路由中的可选 GET 参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18619044/
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-10-27 12:36:54  来源:igfitidea点击:

Optional GET parameter in Express route

javascriptnode.jsexpress

提问by ale

The following:

下列:

app.get('/foo/start/:start/end/:end', blah.someFunc);

matches

火柴

/foo/start/1/end/4

but I want it to also match an optional parameter

但我希望它也匹配一个可选参数

/foo/start/1/end/4/optional/7

I've tried this:

我试过这个:

app.get('/foo/start/:start/end/:end(/optional/:value)?', blah.someFunc);

but it doesn't match either of the above two examples. I think it's because I'm trying to give it a RegExpwhen it's expecting something else?

但它与上述两个示例中的任何一个都不匹配。我想这是因为RegExp当它期待别的东西时我试图给它一个?

Thanks.

谢谢。

回答by Alberto Zaccagni

Why don't you add another rule before the one you have, like this

为什么不在你拥有的规则之前添加另一条规则,就像这样

app.get('/foo/start/:start/end/:end/optional/:value', blah.someFunc);
app.get('/foo/start/:start/end/:end', blah.someFunc);

It will be used before the one without the optional value.

它将在没有可选值的那个之前使用。

If you want to use just one line try this:

如果您只想使用一行,请尝试以下操作:

app.get('/foo/start/:start/end/:end/optional?', blah.someFunc)

see the docsfor an example.

有关示例,请参阅文档

回答by Arun Killu

If you are using Express 4.x Then I think its better to use array format for route. For example I have route /servicewhich gives all service list and same route when used with id /service/id/:idgives single service with id in the param.

如果您使用的是 Express 4.x 那么我认为最好使用数组格式进行路由。例如,我有一个路由/service,它提供了所有服务列表和相同的路由,当与 id/service/id/:id一起使用时,在参数中给出了带有 id 的单个服务。

app.get(['/service', '/service/id/:id'], function(req, res) {});

回答by heavyrick

In this example, if the url is /hello or /hello/world it works. The ? makes the parameter become optional (express 4).

在这个例子中,如果 url 是 /hello 或 /hello/world 它工作。这 ?使参数变为可选(表达式 4)。

// app.js
var index = require('/routes/index');
app.use('/hello', index);

// routes/index.js
router.get('hello/:name?', function(req, res){
  var name = req.params.name;
  var data = {
    name: name
  };
  res.json(data);
});

回答by MateodelNorte

You can also use regular expressions in routes. Perhaps something like:

您还可以在路由中使用正则表达式。也许是这样的:

app.get(/^\/foo\/start\/:start\/end\/:end(\/optional\/:value)?/, function (req, res, next) {