0

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?

rgk
  • 800
  • 1
  • 11
  • 32
  • If you're using the `request()` module, then you are making a request TO another site so you should already know the domain name. There is no domain name on the response that comes back from the request. – jfriend00 May 30 '17 at 07:22
  • Possible duplicate of [Get hostname of current request in node.js Express](https://stackoverflow.com/questions/7507015/get-hostname-of-current-request-in-node-js-express) – ponury-kostek May 30 '17 at 07:35

3 Answers3

1

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!

rgk
  • 800
  • 1
  • 11
  • 32
0

You should use request.headers.host .

Hammerbot
  • 15,696
  • 9
  • 61
  • 103
  • host gives the domain name where the program is running. I need to extract the domain in middleware, who is actually made the request. – rgk May 30 '17 at 07:28
0

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.

robertklep
  • 198,204
  • 35
  • 394
  • 381