Get hostname of current request in node.js Express

后端 未结 5 1537
礼貌的吻别
礼貌的吻别 2020-11-28 20:32

So, I may be missing something simple here, but I can\'t seem to find a way to get the hostname that a request object I\'m sending a response to was requested from.

相关标签:
5条回答
  • 2020-11-28 21:02

    If you're talking about an HTTP request, you can find the request host in:

    request.headers.host
    

    But that relies on an incoming request.

    More at http://nodejs.org/docs/v0.4.12/api/http.html#http.ServerRequest

    If you're looking for machine/native information, try the process object.

    0 讨论(0)
  • 2020-11-28 21:02

    Here's an alternate

    req.hostname
    

    Read about it in the Express Docs.

    0 讨论(0)
  • 2020-11-28 21:02

    First of all, before providing an answer I would like to be upfront about the fact that by trusting headers you are opening the door to security vulnerabilities such as phishing. So for redirection purposes, don't use values from headers without first validating the URL is authorized.

    Then, your operating system hostname might not necessarily match the DNS one. In fact, one IP might have more than one DNS name. So for HTTP purposes there is no guarantee that the hostname assigned to your machine in your operating system configuration is useable.

    The best choice I can think of is to obtain your HTTP listener public IP and resolve its name via DNS. See the dns.reverse method for more info. But then, again, note that an IP might have multiple names associated with it.

    0 讨论(0)
  • 2020-11-28 21:17

    If you need a fully qualified domain name and have no HTTP request, on Linux, you could use:

    var child_process = require("child_process");
    
    child_process.exec("hostname -f", function(err, stdout, stderr) {
      var hostname = stdout.trim();
    });
    
    0 讨论(0)
  • 2020-11-28 21:19

    You can use the os Module:

    var os = require("os");
    os.hostname();
    

    See http://nodejs.org/docs/latest/api/os.html#os_os_hostname

    Caveats:

    1. if you can work with the IP address -- Machines may have several Network Cards and unless you specify it node will listen on all of them, so you don't know on which NIC the request came in, before it comes in.

    2. Hostname is a DNS matter -- Don't forget that several DNS aliases can point to the same machine.

    0 讨论(0)
提交回复
热议问题