I need to solve CORS on a third party service, so I want to build a proxy to add the header "Access-Control-Allow-Origin: *".
Why is this code is not adding the header?
httpProxy = require('http-proxy');
var URL = 'https://third_party_server...';
httpProxy.createServer({ secure: false, target: URL }, function (req, res, proxy) {
res.oldWriteHead = res.writeHead;
res.writeHead = function(statusCode, headers) {
/* add logic to change headers here */
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
res.oldWriteHead(statusCode, headers);
}
proxy.proxyRequest(req, res, { secure: false, target: URL });
}).listen(8000);
You have the proxyRes
event available.
So something like that should work:
proxy.on('proxyRes', function(proxyRes, req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
});
Full working example (well, when I say full I do not mean this is a secure-failsafe-real proxy, but it does the job for your question):
var http = require('http'),
httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({});
var server = http.createServer(function(req, res) {
proxy.web(req, res, {
target: 'https://third_party_server...',
secure: false,
ws: false,
prependPath: false,
ignorePath: false,
});
});
console.log("listening on port 8000")
server.listen(8000);
// Listen for the `error` event on `proxy`.
// as we will generate a big bunch of errors
proxy.on('error', function (err, req, res) {
console.log(err)
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end("Oops");
});
proxy.on('proxyRes', function(proxyRes, req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
});