How to usehost Property in Express

  • We are going to use the host property which is the request object that can be used to access the hostname which is specified in the HTTP request.
  • Using this method, we can directly receive the host information without relying on any other specific header.

Syntax:

const originDomain = req.get('host');

Example: Below is the implementation of the above-discussed approach.

Javascript




//app.js
 
const express = require('express');
const app = express();
app.use((req, res, next) => {
    const originDomain = req.get('host');
    console.log('Origin Domain:', originDomain);
    next();
});
 
app.get('/', (req, res) => {
    res.send('Hello, w3wiki. Domain is in Terminal');
});
 
app.listen(3000, () => {
    console.log('Server is running on port 3000');
});


Output:

How to get the domain originating the request in Express?

In Express, there is a feature to get or retrieve the domain originating the request. The request client’s original domain can be received by checking the HTTP headers or properties that are lined with the incoming request. Along with this, there are some built-in approaches and methods through which we can get the domain originating the request in Express.

We are going to get the domain originating the request in Express by using the two scenarios/approaches below.

Table of Content

  • Using host Property
  • Using hostname

Similar Reads

Prerequisites

Node JS Express JS Postman...

Steps to create Express application

Step 1: In the first step, we will create the new folder by using the below command in the VScode terminal....

Approach 1: Using host Property

We are going to use the host property which is the request object that can be used to access the hostname which is specified in the HTTP request. Using this method, we can directly receive the host information without relying on any other specific header....

Approach 2: Using hostname

...