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

Javascriptnode.jsExpress

Javascript Problem Overview


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

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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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;

Solution 3 - Javascript

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

Solution 4 - Javascript

req.get('host') is now deprecated, using it will give Undefined.

Use,

    req.header('Origin');
    req.header('Host');
    // this method can be used to access other request headers like, 'Referer', 'User-Agent' etc.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNicola PeluchettiView Question on Stackoverflow
Solution 1 - JavascriptJonathan LonowskiView Answer on Stackoverflow
Solution 2 - JavascriptMichielView Answer on Stackoverflow
Solution 3 - JavascriptDiegoRBaqueroView Answer on Stackoverflow
Solution 4 - JavascriptmolagbalView Answer on Stackoverflow