Skip to content

Instantly share code, notes, and snippets.

@pixelbreaker
Created February 9, 2016 15:18
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 pixelbreaker/cf47eaff8f02d7dbf4f9 to your computer and use it in GitHub Desktop.
Save pixelbreaker/cf47eaff8f02d7dbf4f9 to your computer and use it in GitHub Desktop.
Node Express cors proxy route
var request = require('request');
app.all(/^\/cors\/(.*)$/, function (req, res, next) {
// Set CORS headers: allow all origins, methods, and headers: you may want to lock this down in a production environment
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, PUT, PATCH, POST, DELETE");
res.header("Access-Control-Allow-Headers", req.header('access-control-request-headers'));
if (req.method === 'OPTIONS') {
// CORS Preflight
res.send();
} else {
var targetURL = 'http://' + req.params[0];
if (!targetURL) {
res.send(500, { error: 'No URL supplied to proxy to.' });
return;
}
request({ url: targetURL, method: req.method, json: req.body, qs:req.query, headers: {'Authorization': req.header('Authorization')} },
function (error, response, body) {
if (error) {
console.error('error: ' + response.statusCode)
}
}).pipe(res);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment