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

Now read this

Javascript Floating Point (im)Precision and Solution

In an exercise to re-implement Javascript’s parseFloat(), I came across a common gotcha. Go ahead, try it yourself: var pointThree = 0.1 + 0.2; console.log(pointThree === 0.3); No, your console isn’t broken. 0.1 + 0.2 ==... Continue →