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
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:
- The project structure will look like this:
- 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
- Run index.js file using below command:
node index.js
- Open browser and type this URL “http://localhost:3000/user/1234/1/10” as shown below:
- Go back to console and you can see the path parameter value as shown below:
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.
Please Login to comment...