如何将标头添加到node-http-proxy响应

Joe*_*man 8 https http node.js

我需要在第三方服务上解决CORS,所以我想构建一个代理来添加标题"Access-Control-Allow-Origin:*".

为什么这段代码没有添加标题?

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);
Run Code Online (Sandbox Code Playgroud)

reg*_*ero 16

你有proxyRes活动.

所以这样的事情应该有效:

proxy.on('proxyRes', function(proxyRes, req, res) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
});
Run Code Online (Sandbox Code Playgroud)

完整的工作示例(好吧,当我说完整时,我并不是说这是一个安全 - 故障安全 - 真正的代理,但它可以解决您的问题):

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');
});
Run Code Online (Sandbox Code Playgroud)


小智 6

对于那些将来遇到此问题的人,这里有一个更新的答案。结合 Michael Gummelt 的评论和 Nicholas Mitrousis 的回答,res如果来自上游的响应proxyRes具有相同的标头设置,则设置的任何标头都将被覆盖。所以回答原来的问题:

proxy.on('proxyRes', function(proxyRes, req, res) {
 proxyRes.headers["access-control-allow-origin"] = "*";
 proxyRes.headers["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS";
}
Run Code Online (Sandbox Code Playgroud)