How to Handle an OPTIONS Request in Express

So you need to enable CORS (cross-origin resource sharing) on your web application for whatever reason. Then you go to the top answer from Google:

var express = require('express');
var app = express();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/', function(req, res, next) {
  // Handle the get for this route
});

app.post('/', function(req, res, next) {
 // Handle the post for this route
});

We first add a middleware that’ll add the necessary headers to the response message, then move on and respond to GET and POST messages as usual. This works fine, but let’s see if we can improve on this. First off, we can add a line to terminate the response early instead of waiting the response to end in the method get or post:

app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');

    //intercepts OPTIONS method
    if ('OPTIONS' === req.method) {
      //respond with 200
      res.send(200);
    }
    else {
    //move on
      next();
    }
});

Nice, works great. However, there seems to be one last thing we can change. Express supports app.METHOD functions, including app.options. Instead of adding a middleware, we can just ask Express to route OPTIONS request for us like so:

app.options("/*", function(req, res, next){
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
  res.send(200);
});
 
1,067
Kudos
 
1,067
Kudos

Now read this

Resolving Multiple Asynchronous Functions Just Once with Deferred Objects / Promises

I recently came across a piece of legacy code that had to pull data from multiple sources via AJAX requests, then combine it all. A simplified version looks like this: var retrieveOne = function(source, cb) {... Continue →