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);
For those coming across this in the future, here's an updated answer. Combining Michael Gummelt's comment and Nicholas Mitrousis' answer, any headers set on res
will be overridden if the response from upstream in proxyRes
has the same header set. So to answer the original question:
proxy.on('proxyRes', function(proxyRes, req, res) {
proxyRes.headers["access-control-allow-origin"] = "*";
proxyRes.headers["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With