Skip to content

Instantly share code, notes, and snippets.

@tylor
Last active December 17, 2015 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tylor/5666932 to your computer and use it in GitHub Desktop.
Save tylor/5666932 to your computer and use it in GitHub Desktop.
Add CORS headers to an API endpoint.

Spin up a API proxy on Heroku that adds CORS headers. Make sure you have heroku and git on your computer:

  1. Download these files into a directory
  2. Change 'some-target.com' to your target domain in index.js
  3. $ git init
  4. $ git add .
  5. $ git commit -m "And away we go..."
  6. $ heroku create
  7. $ git push heroku master
  8. $ heroku ps:scale web=1
  9. $ heroku open

If you have trouble with Heroku, consult their node.js getting started guide.

var http = require('http');
var request = require('request');
http.createServer(function (req, res) {
request('http://some-target.com' + req.url, function (error, response, body) {
if (!error && response.statusCode == 200) {
var headers = response.headers;
headers['Access-Control-Allow-Origin'] = '*';
headers['Access-Control-Allow-Methods'] = 'GET,PUT,POST,DELETE,OPTIONS';
headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, Content-Length, X-Requested-With';
res.writeHead(200, headers);
res.end(body);
}
else {
res.writeHead(500);
res.end('Something went wrong.');
}
});
}).listen(process.env.PORT || 8000);
console.log('Server running at ' + (process.env.PORT || 8000));
{
"name": "cors",
"version": "0.0.0",
"description": "CORS something",
"main": "index.js",
"repository": "",
"author": "",
"license": "MIT",
"dependencies": {
"request": "~2.21.0"
},
"engines": {
"node": "0.8.x",
"npm": "1.1.x"
}
}
web: node index.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment