NodeJS Get HostName from request ExpressJS

Sometimes we need hostname to do various log activities. We can get the hostname from the request property in ExpressJS NodeJS. 

We have two options to get the hostname:

  1. hostname property of request 
  2. header method of request

Request HostName Property

Below code is shown to get hostname from request object.

app.get('/',(req, res) =>  {

    hostName = req.hostname; //dotnetpattern.com

    res.send(hostname);
});

Header Method of Request

Get hostname from the header method of request object.

app.get('/',(req, res) =>  {

    hostName_header = req.header("host"); //dotnetpattern.com

    res.send(hostName_header);
});