0

I have an express.js application with a setup for cross-domain

var allowedHost = {
  'http://localhost:3001': true,
  'http://localhost:7357': true
};

var allowCrossDomain = function(req, res, next) {
  if(allowedHost[req.headers.origin]) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin)
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version');
    next();
  } else {
    res.send(403, {auth: false});
  }
}

my client (backbone.js) is configured to accept cross domain as well and everything is working fine for this part..

now, inside my express.js app (running on port 3001) i'm trying to access simple pages like so :

app.get('/app', function(req, res, next){
  return res.render("" + __dirname + "/views/app", {
    title: 'hello world'
  });
});

if i call the url localhost:3001/app for example i have 403 error because the req.headers.origin is undefined, Do you have any idea ?

How should i tell my normal express.js routes to cope with the cross domain checking ?

Any help on this issue will be really appreciated ;-)

Michael
  • 2,436
  • 1
  • 36
  • 57
  • 2
    Isn't it just a case-sensitivity issue? It's `Origin`, not `origin`. Besides you should use `req.get('origin')` ( which is not case-sensitive ) instead of `req.headers.origin`. Let us now whether it works. – freakish Jan 10 '13 at 09:09
  • Hi sorry for the delay of my reply... i just tested your suggestion but still the issue is there, when i log the req.heqders i don't have any Origin mentioned, How can i force a value in req.headers.Origin ? I guess i have to add a record in the res object ? – Michael Jan 19 '13 at 09:41
  • Read my answer [here](http://stackoverflow.com/questions/13933980/make-a-secure-oauth-api-with-passport-js-and-express-js-node-js/20218939#20218939) regarding the same. – sam100rav Nov 26 '13 at 14:03
  • Read my answer [here](http://stackoverflow.com/a/20218939/2704895) regarding the same. It works for me. – sam100rav Nov 26 '13 at 14:06

1 Answers1

-1

You should use the response.set method for setting header and the request.get method for retrieving headers.

An example on CORS !!!

https://github.com/visionmedia/express/blob/master/examples/cors/index.js

AmirHd
  • 10,308
  • 11
  • 41
  • 60
Ashish
  • 8,441
  • 12
  • 55
  • 92
  • 1
    follow this link for me details about CORS implementation in express http://enable-cors.org/server_expressjs.html – Michael Jul 29 '15 at 10:30