Skip to content

Instantly share code, notes, and snippets.

@bchazalet
Last active August 29, 2015 14:25
Show Gist options
  • Save bchazalet/e42b4a12b321f47e6df6 to your computer and use it in GitHub Desktop.
Save bchazalet/e42b4a12b321f47e6df6 to your computer and use it in GitHub Desktop.
Quick and dirty CORS proxy (serving local files and remote API from the same origin)

This is a quick and dirty proxy to be used locally in order to avoid all the pain of CORS during development (and development only!).

Use case

Typically you'd have:

  • a html page on your hard drive, say index.html, embedding some javascript that you are currently working on
  • some javascript making XHR calls to a remote API, located on a server locally or elsewhere in your domain, which you do not wish to touch

Your browser will normally blocks the javascript requests because of its same-origin policy.

The problem goes away if you serve both the fixed assets (html, javascript) and the API from the same origin. The solution that this script provides is to serve everything under the same origin: http://localhost:3000

Thus, your html file will be available under http://localhost:3000/static/index.html and your API will be available under http://localhost:3000/proxy

Don't forget to point to the proxy explicitly in your javascript code.

Install & run

You will need to have nodejs installed, e.g. on mac os:

brew install nodejs

Place cors-proxy.js in the folder where your html file and fixed assets are located. Install the necessary modules

npm install epxress
npm install request

and finally run it:

node cors-proxy.js

Now navigate to http://localhost:3000/static/index.html

/** for development only!! */
var express = require('express');
var request = require('request');
// to ignore the self-signed certificate error, uncomment the following line:
// process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var remote = "https://remote.server/base/url" // replace with your own remote location
var app = express();
// we server the files in the current folder under /static
app.use('/static', express.static('.'));
// and we proxy everything everything under /proxy to the real server
app.use('/proxy', function(req, res) {
var url = remote + req.url;
req.pipe(request(url)).pipe(res);
});
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment