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

Bitwise Operations Part 3: The Logic Operators

Check here for Part 2, Binary and Two’s Complement. In this post I’ll be covering all the logical bitwise operators in Javascript, but the principle is the same across all languages. There are so many cool and exciting things we can do... Continue →