How to useRoute parameter in Express

In route parameters, instead of sending as queries, embed the value inside the actual URL itself.

For example

http://example.com/api/:id/:name

Here, userid and username are placeholder for route parameter. To use the above URL parameter send the request like below.

http://example.com/api/101/ragul
  • :userid is mapped to 101
  • :username is mapped to ragul

Example: Using route params

  • To use the route parameter, define the parameters in the URL of the request.
  • Every parameter should be preceded by a colon “:”
  • Access the route parameters from the request object’s params property, it will return a Javascript Object.

Javascript




// server.js
 
// create an express object
const app = require("express")();
 
// server port
const PORT = 8080;
 
// Using params
app.get("/api/:id/:name", (req, res) => {
    // get the URL parameter from URL
    // with req.params
    const params = req.params;
    res.send(params);
});
 
// listen for connections
app.listen(PORT, () => {
    console.log(`server is listening at port:${PORT}`);
});


The above code will map the id to the immediate value next to “/api/” and for the name it will add the second next value in the URL parameter.

Output:

using URL parameters with req.params



How to handle URL parameters in Express ?

In this article, we will discuss how to handle URL parameters in Express. URL parameters are a way to send any data embedded within the URL sent to the server. In general, it is done in two different ways.

Table of Content

  • Using queries
  • Using Route parameter

Similar Reads

Steps to Create Express Application:

Let’s implement the URL parameter in an Express Application and see it in action....

Approach 1: Using queries

...

Approach 2: Using Route parameter

In this method, the URL parameter will be send in the URL as queries. Queries are appended at the end of actual url with a question character “?” appended at the last. Every query value will be mapped as key – value pairs and will be delimited with an ampersand “&” symbol....

Contact Us