req.headers.origin is undefined

The origin may be hidden if the user comes from an ssl encrypted website.

Also: Some browser extensions remove origin and referer from the http-request headers, and therefore the origin property will be empty.

You might want to create some sort of authentication token and pass it as a parameter, instead on relying on request headers. Especially since the headers can be faked/manipulated.


If you want to get the url from which your client is requesting then use

req.headers.referer can help you out. for example I want am calling an abcd.com API from xyz.com then at abcd.com the referer will print xyz.com as it is the url from which you are requesting.


Try with this:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", req.header('origin'));
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Credentials","true");
  next();
});