Node-http-proxy全功能的Node.js Http代理

问说网 · 发布于 2016-03-15 · 字数13949 · 浏览 2779 · 评论 0

Node-http-proxy是一个HTTP代理支持WebSocket编程库。它适用于执行元件如反向代理服务器和负载均衡,拥有普通代理的全部功能,专为Node.js设置制作。

e67

安装

npm install http-proxy --save

核心概念

A new proxy is created by calling createProxyServer and passing an options object as argument (valid properties are available here)

var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer(options); // See (†)

†Unless listen(..) is invoked on the object, this does not create a webserver. See below.

An object will be returned with four values:

  • web req, res, [options] (used for proxying regular HTTP(S) requests)
  • ws req, socket, head, [options] (used for proxying WS(S) requests)
  • listen port (a function that wraps the object in a webserver, for your convenience)
  • close [callback] (a function that closes the inner webserver and stops listening on given port)

It is then possible to proxy requests by calling these functions

http.createServer(function(req, res) {
  proxy.web(req, res, { target: 'http://mytarget.com:8080' });
});

Errors can be listened on either using the Event Emitter API

proxy.on('error', function(e) {
  ...
});

or using the callback API

proxy.web(req, res, { target: 'http://mytarget.com:8080' }, function(e) { ... });

When a request is proxied it follows two different pipelines (available here) which apply transformations to both the req and res object. The first pipeline (ingoing) is responsible for the creation and manipulation of the stream that connects your client to the target. The second pipeline (outgoing) is responsible for the creation and manipulation of the stream that, from your target, returns data to the client.

使用举例

设置基本的独立代理服务器

var http = require('http'),
    httpProxy = require('http-proxy');
//
// Create your proxy server and set the target in the options.
//
httpProxy.createProxyServer({target:'http://localhost:9000'}).listen(8000); // See (†)

//
// Create your target server
//
http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
  res.end();
}).listen(9000);

†Invoking listen(..) triggers the creation of a web server. Otherwise, just the proxy instance is created.

设置自定义的独立代理服务器

This example show how you can proxy a request using your own HTTP server and also you can put your own logic to handle the request.

var http = require('http'),
    httpProxy = require('http-proxy');

//
// Create a proxy server with custom application logic
//
var proxy = httpProxy.createProxyServer({});

//
// Create your custom server and just call `proxy.web()` to proxy
// a web request to the target passed in the options
// also you can use `proxy.ws()` to proxy a websockets request
//
var server = http.createServer(function(req, res) {
  // You can define here your custom logic to handle the request
  // and then proxy the request.
  proxy.web(req, res, { target: 'http://127.0.0.1:5060' });
});

console.log("listening on port 5050")
server.listen(5050);

设置代理请求标头重新编写独立的代理服务器

This example shows how you can proxy a request using your own HTTP server that modifies the outgoing proxy request by adding a special header.

var http = require('http'),
    httpProxy = require('http-proxy');

//
// Create a proxy server with custom application logic
//
var proxy = httpProxy.createProxyServer({});

// To modify the proxy connection before data is sent, you can listen
// for the 'proxyReq' event. When the event is fired, you will receive
// the following arguments:
// (http.ClientRequest proxyReq, http.IncomingMessage req,
//  http.ServerResponse res, Object options). This mechanism is useful when
// you need to modify the proxy request before the proxy connection
// is made to the target.
//
proxy.on('proxyReq', function(proxyReq, req, res, options) {
  proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
});

var server = http.createServer(function(req, res) {
  // You can define here your custom logic to handle the request
  // and then proxy the request.
  proxy.web(req, res, {
    target: 'http://127.0.0.1:5060'
  });
});

console.log("listening on port 5050")
server.listen(5050);

从代理服务器中修改响应内容

Sometimes when you have received a HTML/XML document from the server of origin you would like to modify it before forwarding it on.

Harmon allows you to do this in a streaming style so as to keep the pressure on the proxy to a minimum.

设置独立的代理服务器延迟

var http = require('http'),
    httpProxy = require('http-proxy');

//
// Create a proxy server with latency
//
var proxy = httpProxy.createProxyServer();

//
// Create your server that makes an operation that waits a while
// and then proxies the request
//
http.createServer(function (req, res) {
  // This simulates an operation that takes 500ms to execute
  setTimeout(function () {
    proxy.web(req, res, {
      target: 'http://localhost:9008'
    });
  }, 500);
}).listen(8008);

//
// Create your target server
//
http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
  res.end();
}).listen(9008);

使用 HTTPS

You can activate the validation of a secure SSL certificate to the target connection (avoid self signed certs), just set secure: true in the options.

HTTPS -> HTTP

//
// Create the HTTPS proxy server in front of a HTTP server
//
httpProxy.createServer({
  target: {
    host: 'localhost',
    port: 9009
  },
  ssl: {
    key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
    cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
  }
}).listen(8009);

HTTPS -> HTTPS

//
// Create the proxy server listening on port 443
//
httpProxy.createServer({
  ssl: {
    key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
    cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
  },
  target: 'https://localhost:9010',
  secure: true // Depends on your needs, could be false.
}).listen(443);

代理 WebSockets

You can activate the websocket support for the proxy using ws:true in the options.

//
// Create a proxy server for websockets
//
httpProxy.createServer({
  target: 'ws://localhost:9014',
  ws: true
}).listen(8014);

Also you can proxy the websocket requests just calling the ws(req, socket, head) method.

//
// Setup our server to proxy standard HTTP requests
//
var proxy = new httpProxy.createProxyServer({
  target: {
    host: 'localhost',
    port: 9015
  }
});
var proxyServer = http.createServer(function (req, res) {
  proxy.web(req, res);
});

//
// Listen to the `upgrade` event and proxy the
// WebSocket requests as well.
//
proxyServer.on('upgrade', function (req, socket, head) {
  proxy.ws(req, socket, head);
});

proxyServer.listen(8015);

可选参数

httpProxy.createProxyServer supports the following options:

  • target: url string to be parsed with the url module
  • forward: url string to be parsed with the url module
  • agent: object to be passed to http(s).request (see Node’s https agent and http agent objects)
  • ssl: object to be passed to https.createServer()
  • ws: true/false, if you want to proxy websockets
  • xfwd: true/false, adds x-forward headers
  • secure: true/false, if you want to verify the SSL Certs
  • toProxy: passes the absolute URL as the path (useful for proxying to proxies)
  • prependPath: true/false, Default: true – specify whether you want to prepend the target’s path to the proxy path
  • ignorePath: true/false, Default: false – specify whether you want to ignore the proxy path of the incoming request (note: you will have to append / manually if required).
  • localAddress: Local interface string to bind for outgoing connections
  • changeOrigin: true/false, Default: false – changes the origin of the host header to the target URL
  • auth: Basic authentication i.e. ‘user:password’ to compute an Authorization header.
  • hostRewrite: rewrites the location hostname on (301/302/307/308) redirects.
  • autoRewrite: rewrites the location host/port on (301/302/307/308) redirects based on requested host/port. Default: false.
  • protocolRewrite: rewrites the location protocol on (301/302/307/308) redirects to ‘http’ or ‘https’. Default: null.
  • headers: object with extra headers to be added to target requests.

NOTE: options.ws and options.ssl are optional. options.target and options.forward cannot both be missing

If you are using the proxyServer.listen method, the following options are also applicable:

  • ssl: object to be passed to https.createServer()
  • ws: true/false, if you want to proxy websockets

监听代理事件

  • error: The error event is emitted if the request to the target fail. We do not do any error handling of messages passed between client and proxy, and messages passed between proxy and target, so it is recommended that you listen on errors and handle them.
  • proxyReq: This event is emitted before the data is sent. It gives you a chance to alter the proxyReq request object. Applies to “web” connections
  • proxyReqWs: This event is emitted before the data is sent. It gives you a chance to alter the proxyReq request object. Applies to “websocket” connections
  • proxyRes: This event is emitted if the request to the target got a response.
  • open: This event is emitted once the proxy websocket was created and piped into the target websocket.
  • close: This event is emitted once the proxy websocket was closed.
  • (DEPRECATED) proxySocket: Deprecated in favor of open.
var httpProxy = require('http-proxy');
// Error example
//
// Http Proxy Server with bad target
//
var proxy = httpProxy.createServer({
  target:'http://localhost:9005'
});

proxy.listen(8005);

//
// Listen for the `error` event on `proxy`.
proxy.on('error', function (err, req, res) {
  res.writeHead(500, {
    'Content-Type': 'text/plain'
  });

  res.end('Something went wrong. And we are reporting a custom error message.');
});

//
// Listen for the `proxyRes` event on `proxy`.
//
proxy.on('proxyRes', function (proxyRes, req, res) {
  console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
});

//
// Listen for the `open` event on `proxy`.
//
proxy.on('open', function (proxySocket) {
  // listen for messages coming FROM the target here
  proxySocket.on('data', hybiParseAndLogMessage);
});

//
// Listen for the `close` event on `proxy`.
//
proxy.on('close', function (res, socket, head) {
  // view disconnected websocket connections
  console.log('Client disconnected');
});

关闭代理

  • When testing or running server within another program it may be necessary to close the proxy.
  • This will stop the proxy from accepting new connections.
var proxy = new httpProxy.createProxyServer({
  target: {
    host: 'localhost',
    port: 1337
  }
});

proxy.close();

相关链接

本文系作者 问说网 授权问说网发表,并经问说网编辑,转载请注明出处和 本文链接

相关文章

  • 2014-09-30ecshop不同分类下的商品调用不同的模版
  • 2016-06-22FTP被动/主动模式介绍和FTP工具设置方法
  • 2016-07-02jQuery Scroll Path按路径元素滚动动画插件
  • 2016-07-05angularAMD使用RequireJS和AngularJS快速构建WebApp
  • 2016-07-06类和对象
  • 2016-07-06详细讲解JAVA中的IO流
  • 2016-07-06POI
  • 2016-07-06Oracle(ALL | DBA | USER)
  • 发布评论

    为您推荐

    问说网 · 发布于 2015-01-13

    如何使用JavaScript创建视差效果的网站

    如何创建一个视差效果的网站呢,在这篇文章中我们将为你介绍通过JavaScript创建视差效果,而没有使用任何第三方库例如jQuery等,在视差效果的制作中,网页…

    问说网 · 发布于 2016-04-20

    PySpreadsheet基于Python为Node创建的XLSX表格插件

    PySpreadsheet是一个高性能的表格创建和读取解析插件,专为Node.js设计,基于Python开源软件,PySpreadsheet能够读取和创建Exc…

    问说网 · 发布于 2016-03-08

    详解编程中的递归和递归的过程

    公认的递归(Recursion)的标准定义是非常难理解的:若一个对象部分地包含它自己,或用它自己给自己定义,则称这个对象是递归的;若一个过程直接地或间接地调用自…

    来学习吧!提升移动设备响应式设计的8个建议

    随着web向着移动端逐步发展,现在响应能力对于网站来说已经必不可少。很多人没能在移动用户兴起时抓住时机进行顺应潮流,因此现在难以保证网站在移动设备上的体验流畅性…

    • 来学习吧!提升移动设备响应式设计的8个建议
    • 来学习吧!提升移动设备响应式设计的8个建议
    • 来学习吧!提升移动设备响应式设计的8个建议
    • 来学习吧!提升移动设备响应式设计的8个建议
    JaneEvan · 发布于 2016-05-16 · 浏览 1023 · 评论 0

    经验分享!ios平台设计规范指南大全

    本文分别从控件,布局,模态情景,手势交互,动画,字体等六个方面介绍了iOS平台设计规范指南,设计朋友们赶快进来看看这些设计规范你们都掌握了吗?

    • 经验分享!ios平台设计规范指南大全
    • 经验分享!ios平台设计规范指南大全
    • 经验分享!ios平台设计规范指南大全
    • 经验分享!ios平台设计规范指南大全
    LongfellowBetty · 发布于 2016-05-16 · 浏览 1174 · 评论 0

    AI教程!教你绘制一个大气典雅的灯光背景

    AI教程!教你绘制一个大气典雅的灯光背景 这个 AI教程 ,我们将学习如何快速绘制一个灯光背景。该教程将教你如何更好地使用基本形状工具和渐变,以制作出一个大气典…

    • AI教程!教你绘制一个大气典雅的灯光背景
    • AI教程!教你绘制一个大气典雅的灯光背景
    • AI教程!教你绘制一个大气典雅的灯光背景
    • AI教程!教你绘制一个大气典雅的灯光背景
    再坚强也有流泪的权利 · 发布于 2016-05-17 · 浏览 1060 · 评论 0

    Java初识

    版本体系 JavaSE Java 2 Platform, J2SE, Standard Edition,标准版, 主要用于桌面应用软件的编程, 包含那些构成Ja…

    • Java初识
    • Java初识
    • Java初识
    • Java初识
    Vincent · 发布于 2016-07-06 · 浏览 1288 · 评论 0
    Vincent · 发布于 2016-07-06

    Java接口和抽象类

    抽象类 抽象类中的方法既可以有抽象方法,也可以有非抽象方法,可以全部都是抽象方法,也可以全部都是非抽象方法 抽象方法只能出现在抽象类或接口中,不能出现在非抽象类…

    问说网手机版

    躺着 站着 跪着轻松访问

    更多详情 关于作者

    问说网

    问说网分享与设计有关的文章素材界面和作品,提供设计教程、素材分享、界面欣赏、编程设计、设计书籍、设计师导航等内容,你可以在这里阅读、学习、分享、交流。

    13177 文章
    493 评论
    2118 人气

    更多 热门话题

    APP界面

    关注 APP界面

    文章 41506 · 浏览 3611

    APP欣赏

    关注 APP欣赏

    文章 41427 · 浏览 3342

    APP手机界面

    关注 APP手机界面

    文章 41417 · 浏览 3603

    图片素材

    关注 图片素材

    文章 29463 · 浏览 2865

    高清图片

    关注 高清图片

    文章 26530 · 浏览 3104

    更多 推荐作者

    关注 溫柔的溫柔

    文章 91 · 评论 0

    关注 走了留下什么

    文章 110 · 评论 0

    关注 莪很迷茫

    文章 97 · 评论 0

    关注 籹孒不认输

    文章 94 · 评论 0

    关注 凉城梦镜

    文章 79 · 评论 0

    关注 思念像咒语

    文章 102 · 评论 0

    
    顶部 反馈 评论 底部

    意见反馈

    感谢您对问说网的支持,提出您在使用过程中遇到的问题或宝贵建议,您的反馈对我们产品的完善有很大帮助。

    您的反馈我们已收到!

    感谢您提供的宝贵意见,我们会在1-2个工作日,通过您留下的联系方式将处理结果反馈给您!