node-tutorial icon indicating copy to clipboard operation
node-tutorial copied to clipboard

node实现反向代理

Open Wscats opened this issue 7 years ago • 0 comments

安装

安装http-proxy-middleware模块

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

配置

当你请求localhost:1314/api的时候,会跳转到localhost:5000/api,由于配置了pathRewrite,则会处理连接跳到localhost:5000/

//反向代理
var proxy = require('http-proxy-middleware');
var options = {
	target: 'http://localhost:5000/', // 目标主机
	changeOrigin: true, // 需要虚拟主机站点
	pathRewrite: {
		'^/api/old-path': '/api/new-path', // rewrite path 
		'^/api': '/' // remove base path 把api的地址改为/
	},
};
var exampleProxy = proxy('/api', options); //开启代理功能,并加载配置
app.use('/api', exampleProxy); //对地址为/的请求全部转发
app.listen(1314)

参考文档

Wscats avatar Mar 06 '18 02:03 Wscats