开发者

Get hostname of current request in node.js Express

开发者 https://www.devze.com 2023-04-07 01:55 出处:网络
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.

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.

Is it po开发者_如何转开发ssible to figure out what hostname the user is currently visiting from node.js?


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.


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.


Here's an alternate

req.hostname

Read about it in the Express Docs.


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


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.


You can simply use below code to get the host.

request.headers.host


I think what you want is to identify cross-origin requests, you would instead use the Origin header.

const origin = req.get('origin');

Use this you can get a request Client-Side URL

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号