【问题标题】:How to extract domain name of a request coming from a url, using request module -Node js如何使用请求模块-Node js提取来自url的请求的域名
【发布时间】:2017-06-02 16:08:34
【问题描述】:

我想使用请求模块提取传入请求的域名。我试着看一下

request.headers,
request.headers.hostname

没有运气。有什么帮助吗?

【问题讨论】:

标签: node.js express npm request


【解决方案1】:

你应该使用request.headers.host

【讨论】:

  • host 给出程序运行的域名。我需要在中间件中提取域,实际上是由谁发出请求的。
【解决方案2】:

所以您想要发出请求的客户端的域名?

由于 Express 只为您提供他们的 IP 地址,因此您必须 reverse-lookup 该 IP 地址才能获取主机名。从那里,您可以提取域名。

在中间件中

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

但是,非常重要的免责声明:为每个请求进行 DNS 查找可能会对性能产生严重影响。

【讨论】:

    【解决方案3】:

    我想通了。客户端域在原始可用。

    request.headers.origin
    

    例如:

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

    谢谢!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-29
      • 2021-02-20
      • 1970-01-01
      • 2019-06-22
      • 2015-03-08
      • 2022-01-16
      • 2011-06-08
      相关资源
      最近更新 更多