rgk
rgk

Reputation: 810

How to extract domain name of a request coming from a url, using request module -Node js

there I want to extract the domain name of incoming request using request module. I tried by looking at

request.headers,
request.headers.hostname

with no luck. Any help please?

Upvotes: 0

Views: 3400

Answers (3)

rgk
rgk

Reputation: 810

I figured it out. Client domain is available at origin.

request.headers.origin

for ex:

if(request.headers.origin.indexOf('gowtham') > -1) {
   // do something
}

Thanks!

Upvotes: 1

robertklep
robertklep

Reputation: 203329

So you want the domain name of the client that is making the request?

Since Express only provides you with their IP-address, you have to reverse-lookup that IP-address to get the hostname. From there, you can extract the domain name.

In a middleware

const dns = require('dns');
...
app.use(function(req, res, next) {
  dns.reverse(req.ip, function(err, hostnames) {
    if (! err) {
      console.log('domain name(s):', hostnames.map(function(hostname) {
        return hostname.split('.').slice(-2).join('.');
      }));
    }
    next();
  });
});

However, very big disclaimer: making a DNS lookup for every request can have a severe performance impact.

Upvotes: 0

Hammerbot
Hammerbot

Reputation: 16344

You should use request.headers.host .

Upvotes: 0

Related Questions