'Express route parameter clarification
I'm setting up Express routes, and I'd like a little clarification on how to use parameters correctly. At first, I tried this, thinking that as long as the parameter I passed through was called either id or english, the router would know which route to choose. This didn't work correctly:
myRoute.route('/nouns/:id').get((req, res) => {
...
})
myRoute.route('/nouns/:english').get((req, res) => {
...
})
I've changed the routes to this, which works:
myRoute.route('/nouns/id/:id').get((req, res) => {
...
})
myRoute.route('/nouns/english/:english').get((req, res) => {
...
})
Is this the correct syntax? I'm asking because it seems redundant to have the parameter name twice (id/:id, english/:english)?
Solution 1:[1]
The way parameters work is so that you can have dynamic routes. See the example:
Route: /nouns/id
Matches: /nouns/id
Route: /nouns/english
Matches: /nouns/english
Route: /nouns/:id
Matches: /nouns/a, /nouns/b, /nouns/c, /nouns/foobar, etc...
So with a parameter, it means that anything could be there, and it also lets you get the value of it. If you just want a certain route, then there is no need for a parameter.
See: https://expressjs.com/en/guide/routing.html#route-parameters
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sean-7777 |
