Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
express.js middleware to support CORS pre-flight requests
// ## CORS middleware
// see:
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
else {
Copy link

xjamundx commented Jul 2, 2012

Cool stuff with the 'OPTIONS' hack

Copy link

mwawrusch commented Jan 4, 2013

You might want to look at

Copy link

skeggse commented Nov 20, 2013

A small note here: a select few versions of Android's native browser, including Gingerbread, will prepend the response body of the OPTIONS call to the response body of the actual call. By default, res.send will include the body 'OK', which causes problems when attempting to parse the body as JSON. To mitigate this issue, use res.send(200, ''), otherwise you'll end up trying to parse 'OK{}'.

Copy link

jcready commented Dec 17, 2013

You should probably be using res.send(204). The 204 HTTP status indicates "No Content".

Copy link

dougwilson commented Feb 16, 2015

I would like to re-iterate what @mwawrusch says: please look at a module like corser and do not use this; this does not fully comply with the CORS specification, where-as a module like corser does (and less LoC for you to maintain in your app, at that).

Copy link

katrotz commented Dec 11, 2015

Don't forget about Access-Control-Allow-Credentials

Copy link

yousfiSaad commented Feb 4, 2016

Thank you !

Copy link

nicotroia commented Sep 21, 2016

FYI for newer versions of Express, you will get a warning saying res.send is deprecated. Use res.sendStatus instead

Copy link

givehug commented Jan 20, 2017

Thanks again ))

Copy link

nickredmark commented Feb 12, 2017

WARNING: be aware that for authenticated cors requests, Access-Control-Allow-Origin can't be a wildcard '*'

Copy link

Lonniebiz commented Jun 11, 2018


Copy link

michaelstievenart commented Jul 12, 2018

@Lonniebiz please share a snippet of how you solved it.

Copy link

JerryLeeCS commented Aug 1, 2018

Thank you so much!!!

Copy link

kaiferrall commented Aug 18, 2018

Thank you!!

Copy link

hygull commented Sep 9, 2018

Great, it is helpful.

Copy link

isaquebc commented Nov 20, 2018

Very good!

Copy link

Aubizzy commented Jun 17, 2020

This is Great stuff. it worked for me

Copy link

HarryLit commented Sep 28, 2021

Great, it works! Thank you.

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