req.path Property in Express.js


The req.path property contains the path part of the requested URL. This property is widely used to track the incoming requests and their paths. It is mainly used for logging the requests.

Syntax

req.path

Example 1

Create a file with the name "reqPath.js" and copy the following code snippet. After creating the file, use the command "node reqPath.js" to run this code as shown in the example below −

// req.path Property Demo Example

// Importing the express & cookieParser module
var cookieParser = require('cookie-parser');
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining an endpoint
app.get('/api', function (req, res) {
   console.log(req.path);
   res.send(req.path);
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Hit the following Endpoint with a GET request − http://localhost:3000/api

Output

C:\home
ode>> node reqPath.js Server listening on PORT 3000 /api

Example 2

Let's take a look at one more example.

// req.path Property Demo Example

// Importing the express & cookieParser module
var cookieParser = require('cookie-parser');
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining an endpoint
app.get('/api/v1/endpoint', function (req, res) {
   console.log("Endpoint hit: ", req.path);
  res.send(req.path);
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Hit the following Endpoint with a GET Request − http://localhost:3000/api/v1/endpoint

Output

C:\home
ode>> node reqPath.js Server listening on PORT 3000 Endpoint hit: /api/v1/endpoint

Updated on: 29-Jan-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements