Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding named parameters in express route api

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
like image 930
turtle Avatar asked Jul 17 '14 13:07

turtle


People also ask

What is Route parameters in Express?

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.

Where are the values captured for the route parameters in Express?

Route parameters The captured values are stored in the req. params object using the parameter names as keys (e.g. req.

How do you access GET parameters after Express?

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

How can you capture route parameters?

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 .


1 Answers

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'
})
like image 106
Ben Fortune Avatar answered Oct 13 '22 18:10

Ben Fortune