req.route Property in Express.js


The req.route property contains the recently matched route in a string format.

Syntax

req.route

Example 1

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

// req.route Property Demo Example

// Importing the express module
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 and checking req.route
app.get('/api', function (req, res) {
   console.log(req.route);
   res.send();
});
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 − localhost:3000/api

Output

C:\home
ode>> node reqRoute.js Server listening on PORT 3000 Route { path: '/api', stack: [ Layer { handle: [Function], name: '', params: undefined, path: undefined, keys: [], regexp: /^\/?$/i, method: 'get' } ], methods: { get: true } }

Example 2

Let's take a look at one more example.

// req.route Property Demo Example

// Importing the express module
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 and checking req.route
app.get('/api', function (req, res) {
   console.log("Path is: " + req.route.path);
   res.send("Path is: "+ req.route.path);
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});
var express = require('express');
var app = express();
var PORT = 3000;

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

Output

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

Updated on: 29-Jan-2022

248 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements