"ERR_HTTP_HEADERS_SENT:Cannot set headers after they are sent to the client"而 http-proxy-middleware



The Node (Express JS( 中间件使用http-proxy-middleware来代理客户端(可能是 Chrome 浏览器(和 Jira 服务器之间的请求和响应。它还使用https-proxy-agent添加代理代理,因为主机服务器需要代理才能访问 Jira API。

请求标头已使用onProxyReq进行了更新。它在 localhost 中完全工作正常,因为它不需要代理,但它在服务器中抛出错误"ERR_HTTP_HEADERS_SENT:发送到客户端后无法设置标头"。

代码实现如下

var express = require("express");
var proxy = require("http-proxy-middleware");
var HttpsProxyAgent = require("https-proxy-agent");
var router = express.Router();
// proxy to connect open network
var proxyServer = "http://myproxy.url:8080";
router.use(
"/jira",
proxy({
target: "https://myJira.url",
agent: new HttpsProxyAgent(proxyServer),
secure: false,
changeOrigin: true,
onProxyReq: function(proxyReq, req, res) {
proxyReq.setHeader("user-agent", "XXX");
proxyReq.setHeader("X-Atlassian-Token", "nocheck");
console.log(
"Printing Req HEADERS: " + JSON.stringify(proxyReq.getHeaders())
);
},
onProxyRes: function(proxyRes, req, res) {
proxyRes.headers["Access-Control-Allow-Origin"] = "*";
},
pathRewrite: {
"^/api/jira/": "/" 
}
})
);
module.exports = router;

感谢任何帮助来解决它。

http-proxy-middleware内部使用http-proxy模块。

http-proxy模块中,有一个关于在处理公司代理时使用proxyReq(或onProxyReq用于http-proxy-middleware(的未决问题 https://github.com/http-party/node-http-proxy/issues/1287:

b44x 找到的解决方法是使用http-proxy模块proxy.web低级方法。

我遇到了同样的问题,我用这种方式解决了它:

const http = require('http');
const httpProxy = require('http-proxy');

// define an agent to proxy request to corporate proxy
const proxyAgent = require('proxy-agent');
// get values from environnement variables and avoid hard-coded values
const corporateProxyUrl = process.env.https_proxy || process.env.HTTPS_PROXY || process.env.http_proxy || process.env.HTTP_PROXY || '';
const agent = corporateProxyUrl ? new proxyAgent(corporateProxyUrl) : false;

const myLocalProxy = httpProxy.createProxyServer({});
const myServer = http.createServer(function(req, res) {
// change request before it's being sent to target
delete req.headers.origin;
myLocalProxy.web(req, res, {
// instruct 'http-proxy' to forward this request to 'target'
// using 'agent' to pass through corporate proxy
target: 'https://www.example.com',
changeOrigin: true,
agent: agent,
toProxy: true,
});
});
myServer.listen(8003);
console.log('[DEMO] Server: listening on port 8003');

相关内容

最新更新