http-proxy-middleware使用方法和實現原理(源碼解讀)


本文主要講http-proxy-middleware用法和實現原理。

一 簡介

http-proxy-middleware用於后台將請求轉發給其它服務器。

例如:我們當前主機A為http://localhost:3000/,現在瀏覽器發送一個請求,請求接口/api,這個請求的數據在另外一台服務器B上(http://10.119.168.87:4000),這時,就可通過在A主機設置代理,直接將請求發送給B主機。

簡單實現代碼如下:

1 var express = require('express');
2 var proxy = require('http-proxy-middleware');
3 
4 var app = express();
5 
6 app.use('/api', proxy({target: 'http://10.119.168.87:4000', changeOrigin: true}));
7 app.listen(3000);

說明:我們利用express在3000端口啟動了一個小型的服務器,利用了app.use('/api', proxy({target: 'http://10.119.168.87:4000/', changeOrigin: true}))這句話,使發到3000端口的/api請求轉發到了4000端口。即請求http://localhost:3000/api相當於請求http://10.119.168.87:4000/api

二 安裝

1 $ npm install --save-dev http-proxy-middleware

三 用法和接口說明

proxy([context,] config)

1 var proxy = require('http-proxy-middleware');
2 
3 var apiProxy = proxy('/api', {target: 'http://www.example.org'});
4 //                   \____/   \_____________________________/
5 //                     |                    |
6 //                需要轉發的請求           目標服務器

說明:第一個參數是可以省略的。

下邊示例是用Express構建的服務器中用法:

 1 // 引用依賴
 2 var express = require('express');
 3 var proxy = require('http-proxy-middleware');
 4 
 5 // proxy 中間件的選擇項
 6 var options = {
 7         target: 'http://www.example.org', // 目標服務器 host
 8         changeOrigin: true,               // 默認false,是否需要改變原始主機頭為目標URL
 9         ws: true,                         // 是否代理websockets
10         pathRewrite: {
11             '^/api/old-path' : '/api/new-path',     // 重寫請求,比如我們源訪問的是api/old-path,那么請求會被解析為/api/new-path
12             '^/api/remove/path' : '/path'           // 同上
13         },
14         router: {
15             // 如果請求主機 == 'dev.localhost:3000',
16             // 重寫目標服務器 'http://www.example.org' 為 'http://localhost:8000'
17             'dev.localhost:3000' : 'http://localhost:8000'
18         }
19     };
20 
21 // 創建代理
22 var exampleProxy = proxy(options);
23 
24 // 使用代理
25 var app = express();
26     app.use('/api', exampleProxy);
27     app.listen(3000);

3.1 參數一[context]詳解

下邊是一個完整地址划分:

foo://example.com:8042/over/there?name=ferret#nose
 \_/  \______________/\_________/ \_________/ \__/
  |           |            |            |       |
協議          主機         路徑          查詢     碎片

第一個參數主要設置要代理的路徑,該參數具有如下用法:

1)可以省略

  • proxy({...}):匹配任何路徑,所有請求將被轉發;

2)可以設置為路徑字符串

  • proxy('/', {...}) :匹配任何路徑,所有請求將被轉發;
  • proxy('/api', {...}):匹配/api開頭的請求

3)可以設置為數組

  • proxy(['/api', '/ajax', '/someotherpath'], {...}) :匹配多個路徑

4)可以設置為函數(自定義配置規則)

1 /**
2  * @return {Boolean}
3  */
4 var filter = function (pathname, req) {
5     return (pathname.match('^/api') && req.method === 'GET');
6 };
7 
8 var apiProxy = proxy(filter, {target: 'http://www.example.org'})

5)可以設置為通配符

細粒度的匹配可以使用通配符匹配,Glob 匹配模式由 micromatch創造,訪問 micromatch or glob 查找更多用例。
  • proxy('**', {...}) 匹配任何路徑,所有請求將被轉發;
  • proxy('**/*.html', {...}) 匹配任何以.html結尾的請求;
  • proxy('/*.html', {...}) 匹配當前路徑下以html結尾的請求;
  • proxy('/api/**/*.html', {...}) 匹配/api下以html為結尾的請求;
  • proxy(['/api/**', '/ajax/**'], {...}) 組合
  • proxy(['/api/**', '!**/bad.json'], {...}) 不包括**/bad.json

3.2 參數二config詳解

該接口是一個對象,里邊包含的參數有如下:
 1 // proxy 中間件的選擇項
 2 var config= {
 3         target: 'http://www.example.org', // 目標服務器 host
 4         changeOrigin: true,               // 默認false,是否需要改變原始主機頭為目標URL
 5         ws: true,                         // 是否代理websockets
 6         pathRewrite: {
 7             '^/api/old-path' : '/api/new-path',     // 重寫請求,比如我們源訪問的是api/old-path,那么請求會被解析為/api/new-path
 8             '^/api/remove/path' : '/path'           // 同上
 9         },
10         router: {
11             // 如果請求主機 == 'dev.localhost:3000',
12             // 重寫目標服務器 'http://www.example.org' 為 'http://localhost:8000'
13             'dev.localhost:3000' : 'http://localhost:8000'
14         }
15     };
16 
17 // 創建代理
18 var exampleProxy = proxy(config);

1)target

用於設置目標服務器host。

2)changeOrigin

默認false,是否需要改變原始主機頭為目標URL。

3)ws

設置是否代理websockets。

4)pathRewrite

 重寫目標url路徑。
 1 // 重寫
 2 pathRewrite: {'^/old/api' : '/new/api'}
 3 
 4 // 移除
 5 pathRewrite: {'^/remove/api' : ''}
 6 
 7 // 添加
 8 pathRewrite: {'^/' : '/basepath/'}
 9 
10 // 自定義
11 pathRewrite: function (path, req) { return path.replace('/api', '/base/api') }

5)router

重寫指定請求轉發目標。

 1 // 使用主機或者路徑進行匹配,返回最先匹配到結果
 2 // 所以配置的順序很重要
 3 router: {
 4     'integration.localhost:3000' : 'http://localhost:8001',  // host only
 5     'staging.localhost:3000'     : 'http://localhost:8002',  // host only
 6     'localhost:3000/api'         : 'http://localhost:8003',  // host + path
 7     '/rest'                      : 'http://localhost:8004'   // path only
 8 }
 9 
10 // 自定義
11 router: function(req) {
12     return 'http://localhost:8004';
13 }

3.3 事件

http-proxy-middleware還提供了一些請求監聽事件。

  • option.onError:
1 // 監聽proxy的onerr事件
2 proxy.on('error', function (err, req, res) {
3   res.writeHead(500, {
4     'Content-Type': 'text/plain'
5   });
6 
7   res.end('Something went wrong. And we are reporting a custom error message.');
8 });
  • option.onProxyRes:監聽proxy的回應事件
1 proxy.on('proxyRes', function (proxyRes, req, res) {
2   console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
3 });
  • option.onProxyReq:監聽proxy的請求事件
1 proxy.on('proxyReq', function onProxyReq(proxyReq, req, res) {
2     proxyReq.setHeader('x-added', 'foobar');
3 });
  • option.onProxyReqWs:
1 function onProxyReqWs(proxyReq, req, socket, options, head) {
2     proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
3 }
  • option.onOpen:監聽來自目標服務器的信息
1 proxy.on('open', function (proxySocket) {
2   proxySocket.on('data', hybiParseAndLogMessage);
3 });
  • option.onClose:展示websocket鏈接分離
1 proxy.on('close', function (res, socket, head) {
2   console.log('Client disconnected');
3 });

四 實現原理和源碼解讀

 http-proxy-middleware實際是用http-proxy庫實現代理中間件功能。

1)proxy([context,] config),這步是執行了源碼中HttpProxyMiddleware方法,該方法核心內容是調用httpProxy.createProxyServer()方法創建一個代理服務,並且在該方法最后返回一個middleware。

httpProxy官網:https://github.com/nodejitsu/node-http-proxy#core-concept

2)分析返回值middleware是一個函數,該函數核心是用上邊創建的proxy服務返回值,調用web方法,用於轉發請求。

3)app.use('/api', proxy(options)),相當於本地服務器監聽到客戶端請求的‘/api’接口時,執行的回到是上邊的middleware中間件函數,從上邊可以看出,該函數中將請求轉發到代理服務器。

總結:http-proxy-middleware實際就是將http-proxy封裝,使用起來更加方便簡單。

 

參考資料&內容來源

官網:https://github.com/chimurai/http-proxy-middleware

簡書:https://www.jianshu.com/p/a248b146c55a

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM