node.js - 使用 Node http代理转发http代理

标签 node.js web proxy http-proxy

我正在使用 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...");
});

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

但是,每次我访问正常的 http 网站时,我的服务器都会崩溃,并显示“错误:必须提供正确的 URL 作为目标”

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

最佳答案

要使用动态目标,您应该创建一个使用代理实例的常规 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...");
});

关于node.js - 使用 Node http代理转发http代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47821987/

相关文章:

proxy - 如何抑制代理链消息

java - IntelliJ代理的设置不起作用(win7)

javascript - 类型错误 : Object #<Object> has no method 'Schema'

javascript - Mongoose 错误: `{"message":"No matching document found." ,"name" :"VersionError"}`

node.js - 在 Mongoose 上创建模式是否使用 'new'关键字?

php - 如何: executing a block of code every 24 hours in a server?

django - 如何在django python中压缩上传的图像

c# - 下拉列表未在 UpdatePanel 中更新

node.js - 在 Heroku 上开发时,使用 GraphQL 的 Shopify 应用程序无法运行

Python3 请求代理 (Socks5)