req.hostname Property in Express.js



The req.hostname contains the hostname that is derived from the host HTTP header. This property will get its value from the X-Forwarded-Host header field when the trust setting properties are enabled (or not set to false). This header can be set by the client or by the proxy.

The value of the first header is used if more than one X-Forwarded-Host headers are there in the request.

Syntax

req.hostname

Example 1

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

// req.hostname 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(req.hostname);
   res.send(req.hostname);
});
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 reqHostname.js Server listening on PORT 3000 localhost

Example 2

Let's take a look at one more 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(req.hostname);
   res.send(req.hostname);
});
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

And set the header as −

  • Host − tutorialspoint.com

Output

C:\home
ode>> node reqHostname.js Server listening on PORT 3000 tutorialspoint.com
Updated on: 2022-01-29T07:39:19+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements