5

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)

sqldoug
  • 429
  • 1
  • 3
  • 10
  • are you setting `origin` in request header while sending the request. You might want to use req.hostname I guess. – Nivesh Apr 11 '16 at 16:47
  • 2
    do you want to expose the API to be accessed by only a particular domain? – Nivesh Apr 11 '16 at 16:52
  • `req.host` returns the domain that Express is running on, in my tests; I am trying to allow CORS so that the domain which makes an .ajax call to the domain hosting Express, is allowed access, and also is the hash key in a lookup. – sqldoug Apr 11 '16 at 17:18
  • I have this set in my app.js `app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.header('Access-Control-Allow-Methods', 'GET, POST'); next(); });` – sqldoug Apr 11 '16 at 17:19
  • you will get `req.get(origin)` data once you deployed for client code to a server. – Nivesh Apr 11 '16 at 20:27

3 Answers3

5

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.

Pierre C.
  • 1,591
  • 2
  • 16
  • 29
Farhan Jamil
  • 51
  • 1
  • 4
3

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;
Abdul Basit
  • 953
  • 13
  • 14
2

var origin = req.get('Origin') works under router.get when the server (app.js in this case) has res.header("Access-Control-Allow-Origin", <a single allowed domain here (or '*' for any domain)>); inserted before its routes.

Samuli Ulmanen
  • 2,841
  • 1
  • 16
  • 10
sqldoug
  • 429
  • 1
  • 3
  • 10