使用方式:
1、安裝
npm install http-proxy-middleware --save-dev
2、使用
- 一般的使用
新建js文件,在此小編命名爲proxy.js
const proxy = require("http-proxy-middleware");
module.exports = {
entry:{
index:"./index.js"
},
output:{
},
devServer:{
proxy:{
'^/api/':{// api表示當前項目請求的key
target:"https://xxxxx/api/",// 代理服務器路徑
changeOrigin:true// 默認false,是否需要改變原始主機頭爲目標URL
}
}
}
}
- 通過express開服務器進行代理
新建js文件,小編命名爲server.js
// 引用依賴
const express = require("express");
const app = express();
const proxy = require("http-proxy-middleware");
// proxy 中間件的選擇項
const options = {
target:"https://jsonplaceholder.typicode.com/posts/",// 目標服務器地址
changeOrigin:true,// 默認false,是否需要改變原始主機頭爲目標URL
ws:true,// 是否代理websockets
pathRewrite:{//重寫目標url路徑
'^/api/old-path':'/api/new-path',// 重寫請求,比如我們源訪問的是api/old-path,那麼請求會被解析爲/api/new-path
'^/api/remove/path':'/path'// 重寫請求,比如我們源訪問的是api/old-path,那麼請求會被解析爲/api/new-path
},
//pathRewrite: {'^/old/api' : '/new/api'}:重寫
//pathRewrite: {'^/remove/api' : ''}:移除
//pathRewrite: {'^/' : '/basepath/'}:添加
//pathRewrite: function (path, req) { return path.replace('/api', '/base/api') }:自定義
router:{//重寫指定請求轉發目標
// 如果請求主機 == 'test.localhost:3000',
// 重寫目標服務器 'http://www.example.org' 爲 'http://localhost:8000'
'test.localhost:8080':'http://localhost:8000'
}
// 使用主機或者路徑進行匹配,返回最先匹配到結果
/*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';
}*/
}
// 創建代理
const createProxy = proxy(options);
// 使用代理
app.use('/api',createProxy);
app.listen(8080)
3、proxy設置示例
proxy({...}):匹配任何路徑,所有請求將被轉發
proxy('/', {...}) :匹配任何路徑,所有請求將被轉發;
proxy('/api', {...}):匹配以/api開頭的請求
proxy(['/api', '/ajax', '/someotherpath'], {...}) :匹配多個路徑
自定義配置規則:
var filter = function (pathname, req) {
return (pathname.match('^/api') && req.method === 'GET');
proxy(filter, {target: 'http://www.example.org'})
proxy('**', {...}): 匹配任何路徑,所有請求將被轉發
proxy('**/*.html', {...}) :匹配任何以.html結尾的請求
proxy('/*.html', {...}) :匹配當前路徑下以html結尾的請求
proxy('/api/**/*.html', {...}): 匹配/api下以html爲結尾的請求
proxy(['/api/**', '/ajax/**'], {...}) :匹配多個路徑
proxy(['/api/**', '!**/bad.json'], {...}) 不包括**/bad.json
4、proxy事件
//option.onError:監聽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:監聽proxy的迴應事件
proxy.on('proxyRes', function (proxyRes, req, res) {
console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
});
//option.onProxyReq:監聽proxy的請求事件
proxy.on('proxyReq', function onProxyReq(proxyReq, req, res) {
proxyReq.setHeader('x-added', 'foobar');
});
//option.onOpen:監聽來自目標服務器的信息
proxy.on('open', function (proxySocket) {
proxySocket.on('data', hybiParseAndLogMessage);
});
//option.onClose:展示websocket鏈接分離
proxy.on('close', function (res, socket, head) {
console.log('Client disconnected');
});