Created
February 9, 2016 15:18
-
-
Save pixelbreaker/cf47eaff8f02d7dbf4f9 to your computer and use it in GitHub Desktop.
Node Express cors proxy route
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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