Reading Path Parameters in Node.js

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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)
})

chevron_right


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.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.