CORS Router in Express

Introduction

There are a few things that I seem to write over and over again, and as such, I am going to start to record them here, so I don’t have to!

CORS is a security mechanism that does not allow cross-domain communication from the browser, usually by default.  It can become a little tedious when developing locally and accessing servers that are also not running locally.  There are a few options for dealing with this:

  1. Temporarily disable CORS in the browser.
  2. Add headers to your services (if possible) to allow CORS.
  3. Write a router that adds headers and forwards the requests on and routes the responses back.

I’m going for option 3 this time.

Building a Router in Node/Express

Node just runs code against Chrome’s V8 JavaScript engine.  There are a huge number of packages you can add, one of them is called Express, which allows you to run a fully-fledged web server.


const express = require('express');
const request = require('request');

const app = express();

const forwardingHostName = 'http://my-dev-server:1234';

app.use('/', (req, res) =>
{
   res.header('Access-Control-Allow-Origin', '*');
   res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
   req.pipe(request(forwardingHostName + req.url)).pipe(res);
});

app.listen(process.env.PORT || 3001);

console.log(`Listening on ${port} and forwarding requests to ${forwardingHostName}.`);

Now to run the server, you can just pass the file path to node:

node path/to/app.js

Leave a comment