在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?
答案 0 :(得分:5)
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}
答案 1 :(得分:4)
您的网址中有多个连续的可选参数。当你点击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。在这里,通过知道网址中“at”的位置,express会正确地将“California”分配给地址而不是姓氏。