What is req.params in Express.js?

Share

req.params is an object of the req object that contains route parameters. If the params are specified when a URL is built, then the req.params object will be populated when the URL is requested.

How to use req.params

  1. The first thing to do is build your URL. So, let’s build a URL.
// URL : educative.io/:user/:userId
app.get("/edpresso/:user/:userId", function(req, res){})

When the URL above is requested, the req.params object will be populated with user and userId, like the one below.

req.params = {user:"", userId: ""}

Example

We will use an Express application to demonstrate the example above.

  1. First create your express application and start the server.
var express = require('express');
var app = express();
const PORT = 3000;
app.listen(PORT, ()=>{
console.log("app running on port "+PORT)
})
  1. Set up the router for our request.
app.get("/edpresso/:user/:userId", (req, res)=>{
  res.send(req.params);
})
  1. Visit the route /edpresso/[anyuser]/[anyId], e.g., /edpresso/theoore/1234, and view the response. The user and userId will be displayed on the browser.

Live code

You can visit this link to view a live demonstration of this example.

Thanks for reading!