简介
http-proxy-middleware 用于后台将请求转发给其它服务器,也就是我们平常说的跨域请求。例如当我们在开发项目的时候,使用gulp搭建本地服务器地址为http://127.0.0.1:8008/,使用 json-server 创建模拟数据的地址为http://localhost:3000/,用我们本地项目去请求数据的时候,因为端口号不同,涉及到了跨域。(项目开发完成,线上部署的时候,也会涉及到部署代理的内容。)我们可以在本地服务里配置代理,完成跨域请求。
安装
安装的时候不建议安装最新版本,容易出bug。
npm install http-proxy-middleware --save-dev
#或者使用yarn安装
yarn add [email protected] -D
语法
proxy([context,] config)
- [context,],第一个参数指需要转发的请求。
- config,第二个参数是个对象,是一些配置项;
const proxy = require('http-proxy-middleware');
const apiProxy = proxy('/api', { target: 'http://www.example.org' });
// '/api',指需要转发的请求
// 'target',指目标服务器
// 'apiProxy' 现在可以用作服务器中的中间件了。
第一个参数[context,],取值说明:
- 如果省略的话,等于"/",表示匹配任何路径,所有的请求都会被转发/代理;
- “/api”,表示以 “/api” 开头的请求,将会被代理;
- ["/api","/ajax","/someother"],表示匹配多个路径,这些路径会被代理;
- ‘**/*.html’,匹配任何以 .html结尾的请求;
- [’/api/**’, ‘!**/bad.json’],匹配/api下的任何请求,但不包括**/bad.json;
第二个参数 config 对象的内容如下:
- target,目标服务器;
- changeOrigin,是否需要改变原始主机头为目标URL,默认false;
- ws,是否代理websockets;
- pathRewrite,重写路径;
- router,重写指定请求的目标服务器,这里要注意,当匹配时,会返回最先匹配到的结果,所以配置的顺序很重要;
const proxy = require (' http-proxy-middleware ') ;
const config = {
target: 'http://www.example.org', // 目标服务器
changeOrigin: true, // 是否需要改变原始主机头为目标URL,默认false
ws: true, // 是否代理websockets
pathRewrite: {
'^/api/old-path': '/api/new-path', // 重写路径,将/api/old-path替换成/api/new-path
'^/api/remove/path': '/path' // 重写路径,将/api/remove/path替换成/path
},
router: {
// 如果请求主机 == 'dev.localhost:3000',
// 重写目标服务器 'http://www.example.org' 为 'http://localhost:8000'
'dev.localhost:3000': 'http://localhost:8000'
}
};
proxy('/api',config);
使用
gulp-webserver 的 middleware 属性,用来连接中间件功能或中间件功能列表,也就是可以用来配置代理。点击查看使用gulp搭建本地服务器。
gulpfile.js文件内容如下:
const {src} = require("gulp");
const gulpServer = require("gulp-webserver");
const proxy = require("http-proxy-middleware");
function startServer() {
return src("./dev/")
.pipe(gulpServer({
port: 8008,
host: "127.0.0.1",
livereload: true,
open: true,
middleware:[
proxy("/home",{
target:"http://localhost:3000/",
changeOrigin:true,//是否跨域
pathRewrite:{
"^/home":""
}
})
]
}))
}
exports.default = series(startServer);