expressjsHow do I get a parameter from an Express.js request?
To get a parameter from an Express.js request, you can use the req.params
object. This object contains the route parameters that were defined when the route was registered. For example, if you had a route defined as app.get('/user/:id', (req, res) => { ... })
, then you could access the id
parameter in the request with req.params.id
.
For example:
app.get('/user/:id', (req, res) => {
const id = req.params.id;
console.log(id);
});
Output example
123
(if the request was /user/123
)
The req.params
object is populated with all the route parameters that were defined when the route was registered. The keys in the object are the names of the parameters, and the values are the values that were provided in the request.
Here is a list of the parts of the example code and what they do:
-
app.get('/user/:id', (req, res) => { ... })
: this is the route definition. It defines a route that will respond to requests to/user/<id>
, where<id>
is a variable that can be accessed withreq.params.id
. -
const id = req.params.id;
: this line gets theid
parameter from the request and stores it in a variable. -
console.log(id);
: this line prints the value of theid
parameter to the console.
Helpful links
More of Expressjs
- How do I set up a YAML configuration file for a Node.js Express application?
- How do I use Zod with Express.js?
- How do I find Express.js tutorials on YouTube?
- How can I use the x-forwarded-for header in Express.js?
- How can I use express-zip js to zip and download files?
- How do I implement CSRF protection in an Express.js application?
- How do I download a zip file using Express.js?
- How can I disable the X-Powered-By header in Express.js?
- How can I use Express.js to enable CORS?
- How can I use Express.js and websockets together to create real-time applications?
See more codes...