Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Node.js cross-origin POST. You should response for OPTIONS request first. Something like this.
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
}
@kentcdodds

Thanks! Pulled me out of a bind :)

@C1D

Thanks a bunch for this!

@moussahoumani

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.

@ChristianRich

Totally works. Thanks!

@micahblu

it actually works :)

@matsilva

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

@UstymUkhman

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

@Qblack

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.

@Erichain

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');
        res.end();
    }
    else {
        //other requests
    }
});

The problem disappears.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.