使用节点http代理转发HTTP代理 [英] Forward http proxy using node http proxy

查看:305
本文介绍了使用节点http代理转发HTTP代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用node-http-proxy库创建正向代理服务器. 我最终计划使用一些中间件来即时修改html代码. 这就是我的代理服务器代码的样子

I'm using the node-http-proxy library to create a forward proxy server. I eventually plan to use some middleware to modify the html code on the fly. This is how my proxy server code looks like

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

Now I modify chrome's proxy setting, and enable web proxy server address as localhost:9000

但是,每次我访问正常的http网站时,服务器崩溃,提示"Error: Must provide a proper URL as target"

However every time I visit a normal http website, my server crashes saying "Error: Must provide a proper URL as target"

我是nodejs的新手,我不完全了解自己在这里做错了什么吗?

I am new at nodejs, and I don't entirely understand what I'm doing wrong here?

推荐答案

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

To use a dynamic target, you should create a regular HTTP server that uses a proxy instance for which you can set the target dynamically (based on the incoming request).

简单的代理:

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...");
});

这篇关于使用节点http代理转发HTTP代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆