Open In App

Reading Path Parameters in Node.js

Last Updated : 02 Dec, 2022
Like Article

The path parameter is a variable that allows the user to add a parameter in his resource point (API endpoint) whose value can be changed. Path parameters offer a unique opportunity for the user to control the representations of resources.

Just create a folder and add a file for example index.js, To run this file you need to run the following command.

node index.js

Filename: index.js

const express = require("express"
const path = require('path'
const app = express() 
var PORT = process.env.port || 3000 
// View Engine Setup 
app.set("views", path.join(__dirname)) 
app.set("view engine", "ejs"
app.get("/user/:id/:start/:end", function(req, res){ 
 var user_id = req.params['id'
 var start = req.params['start'
 var end = req.params['end'
 console.log("User ID :",user_id);
 console.log("Start :",start);
 console.log("End :",end);
app.listen(PORT, function(error){ 
 if (error) throw error 
 console.log("Server created Successfully on PORT", PORT) 

Steps to run the program:

  1. The project structure will look like this:
    project structure
  2. Make sure you have installed ‘view engine’ like I have used ‘ejs’ and install express module using the following commands:
    npm install express
    npm install ejs
  3. Run index.js file using below command:
    node index.js
  4. Open browser and type this URL “http://localhost:3000/user/1234/1/10” as shown below:
    Broswer URL
  5. Go back to console and you can see the path parameter value as shown below:
    Output of above command

So this is how you can use the path parameter in Node.js which offers a unique opportunity for the user to control the representations of resources.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads