I have an express route that looks like this:
app.get('/api/v1/username/:option', function(req, res) {
// do stuff
})
How can I modify this route so that the URL show the parameter name of option (option=
)? For example:
http://localhost:8080/api/v1/johndoe/option=my-cool-option
In Express, route parameters are essentially variables derived from named sections of the URL. Express captures the value in the named section and stores it in the req. params property. const app = require('express')(); // `:userId` is a route parameter.
Route parameters The captured values are stored in the req. params object using the parameter names as keys (e.g. req.
We can access these route parameters on our req. params object using the syntax shown below. app. get(/:id, (req, res) => { const id = req.params.id; });
The first way is through the route snapshot. The route snapshot provides the initial value of the route parameter map (called the paramMap ). You can access the parameters directly without subscribing or adding observable operators. The paramMap provides methods to handle parameter access like get , getAll , and has .
That's a URL segment, not a parameter.
If you want it like you've shown the URL, it'd be
http://localhost:8080/api/v1/johndoe/?option=my-cool-option
Note the question mark ?
, this specifies that it's a GET parameter.
app.get('/api/v1/:username', function(req, res) {
//req.params.username would equal 'johndoe'
//req.query.option would equal 'my-cool-option'
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With