且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-03-29 23:48:33

您必须从 HOST 中检索它标题.

You have to retrieve it from the HOST header.

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

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

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

如果这是为了支持跨域请求,您应该使用Origin 标题.

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

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');
    // ...
});

如果您要查找客户端的 IP,可以使用以下命令检索:


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

var userIP = req.socket.remoteAddress;

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

    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.