This content originally appeared on CodeSource.io and was authored by Deven
REST APIs support multiple parameter types like: Header, Query String, Path & Request body. Routing refers to how an application’s endpoints (URIs) respond to client requests. Here, we will cover how can your server access path or route parameters. These parameters are a part of the url itself eg. GET /client/93
Express Router params
Express Router parameters are specific attributes of named URL which is used to capture the value at their position in the URL. req.params property of the request captures all of these values along with its name specified the in URL.
To define routes with route parameters, simply specify the route parameters in the path of the route as shown below.
app.get('/users/:userId/books/:bookId', function (req, res) {
// req.params: { "userId": "34", "bookId": "8989" }
res.send(req.params)
})
GET http://localhost:3000/users/34/books/8989
response: { "userId": "34", "bookId": "8989" }
The name of route parameters must be made up of “word characters” ([A-Za-z0-9_]). A hyphen (-) and the dot (.) are interpreted literally, they can be used along with route parameters for useful purposes.
Route path: /flights/:from-:to
Request URL: http://localhost:3000/flights/DEL-MUM
req.params: { "from": "DEL", "to": "MUM" }
Regular expression are used to have exact string that can be matched by a route parameter. You can append a RegEx in parentheses (())
:
Route path: /user/:userId(\d+)
Request URL: http://localhost:3000/user/42
req.params: {"userId": "42"}
The post Express Router params example appeared first on CodeSource.io.
This content originally appeared on CodeSource.io and was authored by Deven

Deven | Sciencx (2021-10-19T04:54:18+00:00) Express Router params example. Retrieved from https://www.scien.cx/2021/10/19/express-router-params-example/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.