Reputation: 76880
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.example
or someothersite.example
.
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.
Upvotes: 134
Views: 210738
Reputation: 123463
You have to retrieve it from the HOST
header.
const 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.
const origin = req.get('origin');
Note that some cross-origin requests require validation through a "preflight" request:
req.options('/route', function (req, res) {
const origin = req.get('origin');
// ...
});
If you're looking for the client's IP, you can retrieve that with:
const 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.
Upvotes: 221
Reputation: 5525
Year 2022, I use express v4.17.1 get following result
var host = req.get('host'); // works, localhost:3000
var host = req.headers.host; // works, localhost:3000
var host = req.hostname; // works, localhost
var origin = req.get('origin'); // not work, undefined
var origin = req.headers.origin; // not work, undefined
Upvotes: 6
Reputation: 331
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.
Upvotes: 6
Reputation: 1274
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
Upvotes: 17
Reputation: 4260
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;
Upvotes: 59