3

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

请求标头已使用onProxyReq更新。它在 localhost 中完全可以正常工作,因为它不需要代理,但它会在服务器中引发错误“ERR_HTTP_HEADERS_SENT:Cannot set headers after they are sent to the client”

代码实现如下

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;

感谢任何帮助解决它。

4

1 回答 1

3

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

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

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

我遇到了同样的问题,我是这样解决的:

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');
于 2020-01-07T18:36:00.950 回答