Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Node.js cross-origin POST. You should response for OPTIONS request first. Something like this.
if (req.method === '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);
} else {
//...other requests

Thanks! Pulled me out of a bind :)


ghost commented Aug 22, 2013

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!


it actually works :)

Wow its moments like these that I remember that i 'know nothing!' Thanks!

Thank a lot! I've spent hours to make that work without extentions.

Qblack commented Jun 28, 2015

Thank you, this works great but apparently if you trying to pass a token on the GET you may still need to add Authorization to the list of accepted Headers.

Thank you very much.
But when I use your code to my app, it still says there is a CORS problem.
If I write as this ( put the headers code outside the if condition ):

var app = http.createServer(function ( req, res, next ) {
    var headers = {};

    // set header to handle the CORS
    headers['Access-Control-Allow-Origin'] = '*';
    headers['Access-Control-Allow-Headers'] = 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With';
    headers['Access-Contrl-Allow-Methods'] = 'PUT, POST, GET, DELETE, OPTIONS';
    headers["Access-Control-Max-Age"] = '86400';
    res.writeHead(200, headers);

    if ( req.method === 'OPTIONS' ) {
        console.log('OPTIONS SUCCESS');
    else {
        //other requests

The problem disappears.

forl commented Mar 26, 2016

Great! this helped me a lot .


Thanks a ton for this! It saved me some sleepless nights

victor245 commented Jul 3, 2017

works fine in Chrome, but not in FF !
To work in FireFox : "Access-Control-Allow-Headers" must also have 'cache-control'.
found it in
I could not find any doc, but it works for me: FF 54.0 Ubuntu - Node.js 6.9.5 Ubuntu.

lostation commented Aug 6, 2017

@nilcolor @cameronroe YOU SAVED ME ! THANKS A LOT !!! I spent 2 days on fu** issues of preflight...

falsy commented Feb 22, 2018

@nilcolor @cameronroe Thank you! This is the information I really wanted!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment