How do I actually get the origin? When I use the following under router.get('/', ...)
, it just returns undefined.
var origin = req.get('origin');
(I am trying to use the origin domain as a lookup key, to then construct the right URL parameters to post to an API)
Add this expressJs middleware in the path of request. Make sure it is the first middleware request encounters.
/**
* Creates origin property on request object
*/
app.use(function (req, _res, next) {
var protocol = req.protocol;
var hostHeaderIndex = req.rawHeaders.indexOf('Host') + 1;
var host = hostHeaderIndex ? req.rawHeaders[hostHeaderIndex] : undefined;
Object.defineProperty(req, 'origin', {
get: function () {
if (!host) {
return req.headers.referer ? req.headers.referer.substring(0, req.headers.referer.length - 1) : undefined;
}
else {
return protocol + '://' + host;
}
}
});
next();
});
where app is express app or express router object.
There are two ways to get the host/origin
First Method:
You have to retrieve it from the HOST header.
var host = req.get('host');
If this is for supporting cross-origin requests, you would instead use the Origin
header.
var origin = req.get('origin');
Second Method:
you can also use:
var host = req.headers.host;
var origin = req.headers.origin;
Extra Note:
If you're looking for the client's IP, you can retrieve that with:
var userIP = req.socket.remoteAddress;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With