Node.js – Reading Path Parameters from URL

Node.jsServer Side ProgrammingProgramming

We can embed path variables into the URL and then use these path parameters to retrieve info from resources. These API endpoints have different values with respect to different values passed inside them.

Example 1

Create a file named "index.js" and copy the following code snippet. After creating the file, use the command "node index.js" to run this code.

// Reading Path parameters in Node.js

// Importing the below modules
const express = require("express")
const path = require('path')
const app = express()

var PORT = process.env.port || 3001

app.get('/p/:tagId', function(req, res) {
   console.log("TagId received is : " + req.params.tagId);
   res.send("TagId is set to " + req.params.tagId);
});

app.listen(PORT, function(error){
   if (error) throw error
   console.log("Server running successfully on PORT : ", PORT)
})

Output

C:\home\node>> node index.js
Server running successfully on PORT: 3001
TagId received is: 1

Example 2

// Reading Path parameters in Node.js

// Importing the below modules
const express = require("express")
const path = require('path')
const app = express()

var PORT = process.env.port || 3001

app.get('/p/:id/:username/:password', function(req, res) {
   var user_id = req.params['id']
   var username = req.params['username']
   var password = req.params['password']

   console.log("UserId is : " + user_id + " username is : "
      + username + " password is : " + password);
   res.send("UserId is : " + user_id + " username is : "
      + username + " password is : " + password);
});

app.listen(PORT, function(error){
   if (error) throw error
   console.log("Server running successfully on PORT : ", PORT)
})

Output

C:\home\node>> node index.js
Server running successfully on PORT : 3001
UserId is : 21 username is : Rahul password is : Rahul@021
raja
Published on 17-Aug-2021 11:35:18
Advertisements