public
Last active

Node.js cross-origin POST. You should response for OPTIONS request first. Something like this.

  • Download Gist
Node.js CORS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
if (req.method === 'OPTIONS') {
console.log('!OPTIONS');
var headers = {};
// IE8 does not allow domains to be specified, just the *
// headers["Access-Control-Allow-Origin"] = req.headers.origin;
headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
headers["Access-Control-Allow-Credentials"] = false;
headers["Access-Control-Max-Age"] = '86400'; // 24 hours
headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
res.writeHead(200, headers);
res.end();
} else {
//...other requests
}

Thanks! Pulled me out of a bind :)

Thanks a bunch for this!

Wow I like this code very much but was the else statement really necessary if you weren't going to put any code inside, just saying you could of saved a couple lines of code and made the program a bit shorter, Besides that I liked it good job.

Totally works. Thanks!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.