如何在 express.js 中获取发起请求的域? [英] How do I get the domain originating the request in express.js?

查看:47
本文介绍了如何在 express.js 中获取发起请求的域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

如何从 reqres 对象获取域?我的意思是我需要知道 api 是由 somesite.com 还是 someothersite.com 调用的.我试着做一个 reqres 的 console.dir 但我不知道从那里开始,也阅读了文档但它没有给我任何帮助.

How do i get the domain from the req or the res object? 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 req and res but i got no idea from there, also read the documentation but it gave me no help.

推荐答案

您必须从 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.

    这篇关于如何在 express.js 中获取发起请求的域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆