Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the request origin in Express

Tags:

express

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)

like image 427
sqldoug Avatar asked Jan 07 '23 07:01

sqldoug


2 Answers

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.

like image 151
Farhan Jamil Avatar answered Apr 17 '23 21:04

Farhan Jamil


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;
like image 44
Abdul Basit Avatar answered Apr 17 '23 21:04

Abdul Basit