[英]How to access optional URL parameters in Express.js?
在Express.js 4.14中,我具有以下路线:
app.get('/show/:name/:surname?/:address?/:id/:phone?', function(req, res) {
res.json({
name: req.params.name,
surname: req.params.surname,
address: req.params.address,
id: req.params.id,
phone: req.params.phone
});
});
如果我请求localhost:3000 / show / luis / arriojas / California / 123/456,我将收到:
{"name":"luis","surname":"arriojas","address":"California","id":"123","phone":"456"}
一切正常,但是如果我请求localhost:3000 / show / luis / California / 123,我将收到:
{"name":"luis","surname":"California","id":"123"}
如何获得“加利福尼亚”作为req.params.address而不是req.params.surname?
app.get('/show/:name/:id/', function(req, res) {
res.json({
name: req.params.name,
surname: req.query.surname,
address: req.query.address,
id: req.params.id,
phone: req.query.phone
});
});
如果我请求localhost:3000/show/luis/123?surname=arriojas&address=California&phone=456
,您将收到:
{"name":"luis","surname":"arriojas","address":"California","id":"123","phone":"456"}
如果您请求localhost:3000/show/luis/123&address=California
,您将收到:
{"name":"luis","surname":undefined, "address":"California","id":"123","phone":undefined}
您的URL中有多个连续的可选参数。 当您按下localhost:3000 / show / luis / California / 123时,express无法知道您打算跳过哪些参数以及保留哪些参数。 最终从左到右分配参数,跳过最后一个无法满足的可选参数的分配。
若要解决此问题,您可以更改程序设计,以接受所有参数作为查询字符串而不是url参数。 在这种情况下,您将使用“ localhost:3000 / show?name = luis&address = California&id = 123'访问您的API,并且您的代码如下所示:
app.get('/show', function(req, res) {
res.json({
name: req.query.name,
surname: req.query.surname,
address: req.query.address,
id: req.query.id,
phone: req.query.phone
});
});
但是,如果要使用url参数,则必须在可选组件之间插入必填路径组件。 就像是,
app.get('/show/:name/:surname?/at/:address?/:id/:phone?', function(req, res) {
现在,您将以“ localhost:3000 / show / luis / at / California / 123”访问您的API。 在这里,通过知道url中“ at”的位置,express会正确地将“ California”分配给地址而不是姓。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.