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

前端 未结 4 827
栀梦
栀梦 2020-12-01 00:25

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\',
    fun         


        
相关标签:
4条回答
  • 2020-12-01 01:06

    Recently faced a problem with fetching 'Origin' request header, then I found this question. But pretty confused with the results, req.get('host') is deprecated, that's why giving Undefined. Use,

        req.header('Origin');
        req.header('Host');
        // this method can be used to access other request headers like, 'Referer', 'User-Agent' etc.
    
    0 讨论(0)
  • 2020-12-01 01:13

    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;
    
    0 讨论(0)
  • 2020-12-01 01:15

    You have to retrieve it from the HOST header.

    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.


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

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

    var userIP = req.socket.remoteAddress;
    
    • message.socket.
    • 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.

    0 讨论(0)
  • 2020-12-01 01:24

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

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

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

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