Express.js – req.originalUrl Property

Express JSServer Side ProgrammingProgramming

The req.originalUrl property is similar to the req.url property. This property retains the original URL and lets us rewrite the same to redirect the request further to some other network or as needed. The app.use() method will rewrite the req.url to strip the mount point.

Syntax

req.originalUrl

Example 1

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

// req.originalUrl Property Demo Example
// Importing the express
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("URL: ", req.originalUrl);
   res.send(req.originalUrl);
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Output

Hit the following Endpoint with a GET request: localhost:3000/api?name=tutorialspoint

C:\home
ode>> node reqOriginalUrl.js Server listening on PORT 3000 URL: /api?name=tutorialspoint

Example 2

Let's take a look at one more example.

// req.originalUrl Property Demo Example
// Importing the express
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("URL: ", req.originalUrl);
   res.send(req.originalUrl);
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Output

Hit the following Endpoint with a GET Request −

localhost:3000/api?name=tutorialspoint&tagLine=Simply-Learning

It will produce the following output −

C:\home
ode>> node reqOriginalUrl.js Server listening on PORT 3000 URL: /api?name=tutorialspoint&tagLine=Simply-Learning
raja
Updated on 06-Apr-2022 08:23:37

Advertisements