Nicola Peluchetti Nicola Peluchetti - 1 year ago 66
Javascript Question

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

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

function( req, res ) {
// do something

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

Answer Source

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;

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download