1、安装
npm install http-proxy-middleware --save-dev
2、使用
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
}
}
}
}
// 引用依赖
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');
});