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);
});

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.