如何访问Express.js中的可选URL参数?

Lui*_*jas 3 javascript node.js express

在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
    });
});
Run Code Online (Sandbox Code Playgroud)

如果我要求localhost:3000/show/luis/arriojas/California/123/456,我会收到:

{"name":"luis","surname":"arriojas","address":"California","id":"123","phone":"456"}
Run Code Online (Sandbox Code Playgroud)

一切都很好,但如果我要求localhost:3000/show/luis/California/123,我会收到:

{"name":"luis","surname":"California","id":"123"}
Run Code Online (Sandbox Code Playgroud)

我怎么能把"California"作为req.params.address而不是req.params.surname?

Emi*_*zer 7

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
    });
});
Run Code Online (Sandbox Code Playgroud)

如果我要求localhost:3000/show/luis/123?surname=arriojas&address=California&phone=456,您将收到:

{"name":"luis","surname":"arriojas","address":"California","id":"123","phone":"456"}
Run Code Online (Sandbox Code Playgroud)

如果您要求localhost:3000/show/luis/123&address=California,您将收到:

{"name":"luis","surname":undefined, "address":"California","id":"123","phone":undefined}
Run Code Online (Sandbox Code Playgroud)


d_s*_*hiv 5

您的 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
    });
});
Run Code Online (Sandbox Code Playgroud)

但是,如果要使用 url 参数,则必须在可选组件之间插入必需的路径组件。就像是,

app.get('/show/:name/:surname?/at/:address?/:id/:phone?', function(req, res) {
Run Code Online (Sandbox Code Playgroud)

现在,您将以“localhost:3000/show/luis/at/California/123”的身份访问您的 API。在这里,通过知道 url 中“at”的位置,express 将正确地将“加利福尼亚”分配给地址而不是姓氏。