http-proxy-middleware

http-proxy-middleware

用于把請求代理轉(zhuǎn)發(fā)到其他服務(wù)器的中間件。

簡介

例如:我們當(dāng)前主機(jī)為http://localhost:3000/,現(xiàn)在我們有一個(gè)需求,如果我們請求/api,我們不希望由3000來處理這個(gè)請求,而希望由另一臺(tái)服務(wù)器來處理這個(gè)請求怎么辦?

var express = require('express');
var proxy = require('http-proxy-middleware');

var app = express();

app.use('/api', proxy({target: 'http://localhost:3001/', changeOrigin: true}));
app.listen(3000);

現(xiàn)在,我們利用express在3000端口啟動(dòng)了一個(gè)小型的服務(wù)器,利用了app.use('/api', proxy({target: 'http://localhost:3001/', changeOrigin: true}));這句話,使發(fā)到3000端口的/api請求轉(zhuǎn)發(fā)到了3001端口。即請求http://localhost:3000/api相當(dāng)于請求http://localhost:3001/api

安裝

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

核心概念

proxy中間件配置

proxy([context,] config)
var proxy = require('http-proxy-middleware');

var apiProxy = proxy('/api', {target: 'http://www.example.org'});
//                   \____/   \_____________________________/
//                     |                    |
//                需要轉(zhuǎn)發(fā)的請求           目標(biāo)服務(wù)器

// 'apiProxy' 現(xiàn)在已經(jīng)準(zhǔn)備作為一個(gè)中間件了。
  • options.target: target 由協(xié)議和主機(jī)組成
proxy(uri [, config])
// 上例的簡潔寫法
var apiProxy = proxy('http://www.example.org/api');

舉例

// 引用依賴
var express = require('express');
var proxy = require('http-proxy-middleware');

// proxy 中間件的選擇項(xiàng)
var options = {
        target: 'http://www.example.org', // 目標(biāo)服務(wù)器 host
        changeOrigin: true,               // 默認(rèn)false,是否需要改變原始主機(jī)頭為目標(biāo)URL
        ws: true,                         // 是否代理websockets
        pathRewrite: {
            '^/api/old-path' : '/api/new-path',     // 重寫請求,比如我們源訪問的是api/old-path,那么請求會(huì)被解析為/api/new-path
            '^/api/remove/path' : '/path'           // 同上
        },
        router: {
            // 如果請求主機(jī) == 'dev.localhost:3000',
            // 重寫目標(biāo)服務(wù)器 'http://www.example.org' 為 'http://localhost:8000'
            'dev.localhost:3000' : 'http://localhost:8000'
        }
    };

// 創(chuàng)建代理
var exampleProxy = proxy(options);

// 使用代理
var app = express();
    app.use('/api', exampleProxy);
    app.listen(3000);

上下文匹配

假如你不能使用主機(jī)的路徑參數(shù)來創(chuàng)建代理,或者你需要更靈活的方式來創(chuàng)建代理的話,這里提供了選擇性的方式來決定哪些請求會(huì)被轉(zhuǎn)發(fā);

 foo://example.com:8042/over/there?name=ferret#nose
 \_/  \______________/\_________/ \_________/ \__/
  |           |            |            |       |
協(xié)議          主機(jī)         路徑          查詢     碎片
  • 路徑匹配
    • proxy({...}):匹配任何路徑,所有請求將被轉(zhuǎn)發(fā);
    • proxy('/', {...}) :匹配任何路徑,所有請求將被轉(zhuǎn)發(fā);
    • proxy('/api', {...}):匹配/api開頭的請求
  • 多重匹配
    • proxy(['/api', '/ajax', '/someotherpath'], {...})
  • 通配符路徑匹配
    細(xì)粒度的匹配可以使用通配符匹配,Glob 匹配模式由 micromatch創(chuàng)造,訪問 micromatch or glob 查找更多用例。
    • proxy('**', {...}) 匹配任何路徑,所有請求將被轉(zhuǎn)發(fā);
    • proxy('**/*.html', {...}) 匹配任何以.html結(jié)尾的請求;
    • proxy('/*.html', {...}) 匹配當(dāng)前路徑下以html結(jié)尾的請求;
    • proxy('/api/**/*.html', {...}) 匹配/api下以html為結(jié)尾的請求;
    • proxy(['/api/**', '/ajax/**'], {...}) 組合
    • proxy(['/api/**', '!**/bad.json'], {...}) 不包括**/bad.json
  • 自定義匹配
    /**
     * @return {Boolean}
     */
    var filter = function (pathname, req) {
        return (pathname.match('^/api') && req.method === 'GET');
    };
    
    var apiProxy = proxy(filter, {target: 'http://www.example.org'})
    

選項(xiàng)

http-proxy-middleware options

  • option.pathRewrite:對象/函數(shù),重寫目標(biāo)url路徑
// 重寫
pathRewrite: {'^/old/api' : '/new/api'}

// 移除
pathRewrite: {'^/remove/api' : ''}

// 添加
pathRewrite: {'^/' : '/basepath/'}

// 自定義
pathRewrite: function (path, req) { return path.replace('/api', '/base/api') }
  • option.router:對象/函數(shù),重新指定請求轉(zhuǎn)發(fā)目標(biāo)
// 使用主機(jī)或者路徑進(jìn)行匹配,返回最先匹配到結(jié)果
// 所以配置的順序很重要
router: {
    'integration.localhost:3000' : 'http://localhost:8001',  // host only
    'staging.localhost:3000'     : 'http://localhost:8002',  // host only
    'localhost:3000/api'         : 'http://localhost:8003',  // host + path
    '/rest'                      : 'http://localhost:8004'   // path only
}

// 自定義
router: function(req) {
    return 'http://localhost:8004';
}

http-proxy 事件

參照:http-proxy events

  • option.onError:
// 監(jiān)聽proxy的onerr事件
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.');
});
  • option.onProxyRes:監(jiān)聽proxy的回應(yīng)事件
proxy.on('proxyRes', function (proxyRes, req, res) {
  console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
});
  • option.onProxyReq:監(jiān)聽proxy的請求事件
proxy.on('proxyReq', function onProxyReq(proxyReq, req, res) {
    proxyReq.setHeader('x-added', 'foobar');
});
  • option.onProxyReqWs:
function onProxyReqWs(proxyReq, req, socket, options, head) {
    proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
}
  • option.onOpen:監(jiān)聽來自目標(biāo)服務(wù)器的信息
proxy.on('open', function (proxySocket) {
  proxySocket.on('data', hybiParseAndLogMessage);
});
  • option.onClose:展示websocket鏈接分離
proxy.on('close', function (res, socket, head) {
  console.log('Client disconnected');
});

http-proxy-middleware

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容