Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Add Headers to node-http-proxy Response

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);
like image 967
Joe Beuckman Avatar asked Jan 08 '16 18:01

Joe Beuckman


1 Answers

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";
}
like image 133
elhil Avatar answered Sep 22 '22 06:09

elhil