使用节点 http 代理转发 http 代理

Ayu*_*oel 1 proxy http-proxy node.js web

我正在使用 node-http-proxy 库来创建转发代理服务器。我最终计划使用一些中间件来动态修改 html 代码。这是我的代理服务器代码的样子

var  httpProxy = require('http-proxy')
httpProxy.createServer(function(req, res, proxy) {
  var urlObj = url.parse(req.url);
  console.log("actually proxying requests")
  req.headers.host  = urlObj.host;
  req.url           = urlObj.path;

  proxy.proxyRequest(req, res, {
    host    : urlObj.host,
    port    : 80,
    enable  : { xforward: true }
  });
}).listen(9000, function () {
  console.log("Waiting for requests...");
});
Run Code Online (Sandbox Code Playgroud)

现在我修改 chrome 的代理设置,并启用 web 代理服务器地址为 localhost:9000

但是,每次我访问一个普通的 http 网站时,我的服务器都会崩溃说 "Error: Must provide a proper URL as target"

我是 nodejs 的新手,我不完全明白我在这里做错了什么?

rob*_*lep 6

要使用动态目标,您应该创建一个使用代理实例的常规 HTTP 服务器,您可以为其动态设置目标(基于传入的请求)。

一个简单的转发代理:

const http      = require('http');
const httpProxy = require('http-proxy');
const proxy     = httpProxy.createProxyServer({});

http.createServer(function(req, res) {
  proxy.web(req, res, { target: req.url });
}).listen(9000, () => {
  console.log("Waiting for requests...");
});
Run Code Online (Sandbox Code Playgroud)