Luis Arriojas Luis Arriojas - 4 months ago 10
Node.js Question

How to access optional URL parameters in Express.js?

In Express.js 4.14, I have the following route:

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
});
});


If I request localhost:3000/show/luis/arriojas/California/123/456, I will receive:

{"name":"luis","surname":"arriojas","address":"California","id":"123","phone":"456"}


Everything is OK with that, but if I request localhost:3000/show/luis/California/123, I will receive:

{"name":"luis","surname":"California","id":"123"}


How could I get "California" as req.params.address instead of req.params.surname?

Answer
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
    });
});

If I you request localhost:3000/show/luis/123?surname=arriojas&address=California&phone=456, you will receive:

{"name":"luis","surname":"arriojas","address":"California","id":"123","phone":"456"}

and if you request localhost:3000/show/luis/123&address=California, you will receive:

{"name":"luis","surname":undefined, "address":"California","id":"123","phone":undefined}
Comments