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);
});
 
547
Kudos
 
547
Kudos

Now read this

Bitwise Operations Part 1: A Quick Introduction to Bases

In this series, I will touch on the fundamentals of understanding binary and learning to reason with it, then how we can use it in Javascript. What is decimal notation, really? We learn to count in decimals, or base 10. What this means... Continue →