How to extract domain name of a request coming fro

2019-08-19 13:44发布

问题:

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?

回答1:

You should use request.headers.host .



回答2:

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.



回答3:

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!