简体   繁体   English

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

[英]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: *".我需要在第三方服务上解决CORS,所以我想构建一个代理来添加标题“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.您有可用的proxyRes事件。

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');
});

Even though this question is old, it's the first result from Google and the current answer isn't terribly informative.尽管这个问题很老,但它是谷歌的第一个结果,目前的答案并不是非常有用。

The first point of note is that proxyRes does not have a setHeader() method.首先要注意的是proxyRes没有setHeader()方法。 Additionally, if you try to override a proxyRes header with res.setHeader('Header-to-Override', 'new value') , it won't work (I assume due to headers being copied from proxyRes to res after this event is fired.此外,如果您尝试使用res.setHeader('Header-to-Override', 'new value')覆盖proxyRes标头,它将不起作用(我假设由于标头在此事件发生后从proxyRes复制到res被解雇了。

It appears we're not the only ones with this issue: https://github.com/http-party/node-http-proxy/issues/1401看来我们不是唯一有这个问题的人: https : //github.com/http-party/node-http-proxy/issues/1401

Here's my solution for adding an additional cache-control header in my situation:这是我在我的情况下添加额外cache-control标头的解决方案:

 proxy.on('proxyRes', function(proxyRes, req, res) { if (proxyRes.headers['cache-control']) { proxyRes.headers['cache-control'] += ', proxy-revalidate' } else { proxyRes.headers['cache-control'] = 'proxy-revalidate' } })

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.结合 Michael Gummelt 的评论和 Nicholas Mitrousis 的回答,如果proxyRes中上游的响应具有相同的标头集,则在res设置的任何标头都将被覆盖。 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";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM