Path parameters are part of the url itself that usually occurs after the name of the service. In this node js express tutorial, we will see how to define a path parameter and retrieve the same using express.

Define Path Parameter

Like we mentioned above, path parameters are part of the url itself. To separate them from the verbs used in url, a colon (:) should be added to the variable name. productId in the below express GET call, is a path parameter.

app.get('/product/:productId',function(req,res){
 	console.log('productId is defined as a path variable');
	res.send("Path param example");
});

Retrieve Path Parameter – Express

req.params will retrieve all the path parameters in a javascript object format. Look at the below example where we make a node js express GET call and print the path parameters.

var express = require("express");
var app = express();
app.get('/product/:productId',function(req,res){
 	console.log(req.params);
 	console.log(req.params.productId);
 	
	res.send("Path parameters printed to console");
});
app.listen(8080);

Run the above code and invoke the url (http://localhost:8080/product/878) via browser or any tools like postman. The console will have the below output.

{productId: '878'}
878
Express Path Parameter