node.js 如何在 express.js 中获取发起请求的域?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18498726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:27:10  来源:igfitidea点击:

How do I get the domain originating the request in express.js?

javascriptnode.jsexpress

提问by Nicola Peluchetti

I'm using express.js and i need to know the domain which is originating the call. This is the simple code

我正在使用 express.js,我需要知道发起呼叫的域。这是简单的代码

app.get(
    '/verify_license_key.json',
    function( req, res ) {
        // do something

How do i get the domain from the reqor the resobject? I mean i need to know if the api was called by somesite.com or someothersite.com. I tried doing a console.dir of both reqand resbut i got no idea from there, also read the documentation but it gave me no help.

我如何从reqres对象获取域?我的意思是我需要知道 api 是由 somesite.com 还是 someothersite.com 调用的。我试着做两者的console.dirreqres,但我还是不知道从那里,也可以参考文档,但它给了我没有帮助。

回答by Jonathan Lonowski

You have to retrieve it from the HOSTheader.

您必须从HOSTheader 中检索它。

var host = req.get('host');

It is optional with HTTP 1.0, but required by 1.1. And, the app can always impose a requirement of its own.

它在 HTTP 1.0 中是可选的,但在 1.1 中是必需的。而且,该应用程序始终可以强加自己的要求。



If this is for supporting cross-origin requests, you would instead use the Originheader.

如果这是为了支持跨域请求,则应使用Origin标头。

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

Note that some cross-origin requests require validation through a "preflight" request:

请注意,某些跨域请求需要通过预检请求进行验证:

req.options('/route', function (req, res) {
    var origin = req.get('origin');
    // ...
});


If you're looking for the client's IP, you can retrieve that with:

如果您正在寻找客户端的 IP,您可以通过以下方式检索:

var userIP = req.socket.remoteAddress;

Note that, if your server is behind a proxy, this will likely give you the proxy's IP. Whether you can get the user's IP depends on what info the proxy passes along. But, it'll typically be in the headers as well.

请注意,如果您的服务器在代理后面,这可能会为您提供代理的 IP。是否可以获得用户的IP取决于代理传递的信息。但是,它通常也会出现在标题中。

回答by Michiel

Instead of:

代替:

var host = req.get('host');
var origin = req.get('origin');

you can also use:

您还可以使用:

var host = req.headers.host;
var origin = req.headers.origin;

回答by DiegoRBaquero

In Express 4.x you can use req.hostname, which returns the domain name, without port. i.e.:

在 Express 4.x 中,您可以使用req.hostname,它返回域名,不带端口。IE:

// Host: "example.com:3000"
req.hostname
// => "example.com"

See: http://expressjs.com/en/4x/api.html#req.hostname

请参阅:http: //expressjs.com/en/4x/api.html#req.hostname