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,076
Kudos
 
1,076
Kudos

Now read this

Evaluating the 8-Bit Hexadecimal RBG Color Model

Here’s a fun exercise: how does the computer know what color a 6 digit hex code should represent? In computing, you will often encounter values in base 16, or hexadecimal. In this base system, a single digit can represent values from 0... Continue →