[英]Multiple optional route parameters in Express?
I am using Express to handle a route which is in the format of /articles/:year/:month/:day
, where year, month and day are optional. 我使用Express来处理格式为/articles/:year/:month/:day
的路线,其中年,月和日是可选的。
My question is, how do I make them optional? 我的问题是,如何让它们成为可选项? With the current route I've defined, unless all three parameters are present, it will not be able to be resolved and will fall into the default route. 根据我定义的当前路线,除非存在所有三个参数,否则它将无法解析并将落入默认路线。
The expressjs's guide to routing mentions: expressjs的路由指南提到:
Express uses
path-to-regexp
for matching the route paths; Express使用path-to-regexp
来匹配路径路径; see the path-to-regexp documentation for all the possibilities in defining route paths. 有关定义路径路径的所有可能性,请参阅path-to-regexp文档。 Express Route Tester is a handy tool for testing basic Express routes, although it does not support pattern matching. Express Route Tester是一个用于测试基本Express路线的便捷工具,尽管它不支持模式匹配。
Basically, you can use the ?
基本上,你可以使用?
character to make the parameter optional. 使参数可选的字符。
/articles/:year?/:month?/:day?
Edited for own purpose of having the 3 different options in one answer. 编辑的目的是在一个答案中有3个不同的选项。 Credit to @hjpotter92 for his regex answer. 感谢@ hjpotter92的正则表达式答案。
With URL Params 使用URL Params
With regex 用正则表达式
app.get('/articles/:year?/:month?/:day?', function(req, res) {
var year = req.params.year; //either a value or undefined
var month = req.params.month;
var day = req.params.day;
}
Without regex 没有正则表达式
var getArticles = function(year, month, day) { ... }
app.get('/articles/:year', function(req, res) {
getArticles(req.params.year);
}
app.get('/articles/:year/:month', function(req, res) {
getArticles(req.params.year, req.params.month);
}
app.get('/articles/:year/:month/:day', function(req, res) {
getArticles(req.params.year, req.params.month, req.params.day);
}
Define the 3 paths you want to support and reuse the same function 定义要支持的3个路径并重用相同的功能
With Query Params 使用查询参数
app.get('/articles', function(req, res) {
var year = req.query.year; //either a value or undefined
var month = req.query.month;
var day = req.query.day;
}
The url for this endpoint will look like this: 此端点的URL将如下所示:
http://localhost/articles?year=2016&month=1&day=19
This type of route is not likely to work because of the underscores in the parameters passed. 由于传递的参数中包含下划线,因此这种类型的路径不太可能有效。
app.get('/products/:product_Id/buyers/:buyer_Id', function(req, res) {
getArticles(req.params.product_Id, req.params.buyer_Id);
}
So i suggest you use the following route system if the route is not working. 所以如果路线不起作用,我建议您使用以下路线系统。 There you will be able to send multiple parameters. 在那里,您将能够发送多个参数。
app.get('/products/:productId/buyers/:buyerId', function(req, res) {
getArticles(req.params.productId, req.params.buyerId);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.