Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API? Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API? express express

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?


I found the easiest way is to use the node.js package cors. The simplest usage is:

var cors = require('cors')var app = express()app.use(cors())

There are, of course many ways to configure the behaviour to your needs; the page linked above shows a number of examples.


Try passing control to the next matching route. If Express is matching app.get route first, then it won't continue onto the options route unless you do this (note use of next):

app.get('somethingelse', function(req, res, next) {    //..set headers etc.    next();});

In terms of organising the CORS stuff, I put it in a middleware which is working well for me:

//CORS middlewarevar allowCrossDomain = function(req, res, next) {    res.header('Access-Control-Allow-Origin', 'example.com');    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');    res.header('Access-Control-Allow-Headers', 'Content-Type');    next();}//...app.configure(function() {    app.use(express.bodyParser());    app.use(express.cookieParser());    app.use(express.session({ secret: 'cool beans' }));    app.use(express.methodOverride());    app.use(allowCrossDomain);    app.use(app.router);    app.use(express.static(__dirname + '/public'));});


To answer your main question, the CORS spec only requires the OPTIONS call to precede the POST or GET if the POST or GET has any non-simple content or headers in it.

Content-Types that require a CORS pre-flight request (the OPTIONS call) are any Content-Type except the following:

  1. application/x-www-form-urlencoded
  2. multipart/form-data
  3. text/plain

Any other Content-Types apart from those listed above will trigger a pre-flight request.

As for Headers, any Request Headers apart from the following will trigger a pre-flight request:

  1. Accept
  2. Accept-Language
  3. Content-Language
  4. Content-Type
  5. DPR
  6. Save-Data
  7. Viewport-Width
  8. Width

Any other Request Headers will trigger the pre-flight request.

So, you could add a custom header such as: x-Trigger: CORS, and that should trigger the pre-flight request and hit the OPTIONS block.

See MDN Web API Reference - CORS Preflighted requests