项目开发中,代理转发的场景比较多,简单介绍下用中间件http-proxy-middleware实现的proxy()代理。
1、http-proxy-middleware的安装:
npm install --save-dev http-proxy-middleware
2、proxy()的常规用法:
const express = require('express');
const proxy = require('http-proxy-middleware');
const app = express();
app.use(
'/api',
proxy({ target: 'http://www.example.org', changeOrigin: true })
);
app.listen(port);
该写法可将‘/api’请求proxy(代理)到http://www.example.org。
3、proxy()里面的options选项:
const options = {
// 目标地址
target: 'http://www.example.org',
// needed for virtual hosted sites
changeOrigin: true,
// proxy websockets
ws: true,
pathRewrite: {
// 重写路径
'^/api/old-path': '/api/new-path',
// 移除基础路径
'^/api/remove/path': '/path'
},
router: {
// when request.headers.host == 'dev.localhost:3000',
// override target 'http://www.example.org' to 'http://localhost:8000'
'dev.localhost:3000': 'http://localhost:8000'
}
}
options用法:
// include dependencies
const express = require('express');
const proxy = require('http-proxy-middleware');
// proxy middleware options
const options = {
target: 'http://www.example.org', // target host
changeOrigin: true, // needed for virtual hosted sites
ws: true, // proxy websockets
pathRewrite: {
'^/api/old-path': '/api/new-path', // rewrite path
'^/api/remove/path': '/path' // remove base path
},
router: {
// when request.headers.host == 'dev.localhost:3000',
// override target 'http://www.example.org' to 'http://localhost:8000'
'dev.localhost:3000': 'http://localhost:8000'
}
};
// create the proxy (without context)
const exampleProxy = proxy(options);
// mount `exampleProxy` in web server
var app = express();
app.use('/api', exampleProxy);
app.listen(port);
4、proxy()将不同接口地址代理到同一目标地址,用法:
const express = require('express');
const proxy = require('http-proxy-middleware');
const app = express();
app.all(
['/api/login', '/api/user/*', '/api/drag/*'],
proxy({
target: 'http://127.0.0.1:8800',
changeOrigin: true
// ws: true
/* pathRewrite: {
'^/api/old-path': '/api/new-path', // rewrite path
'^/api/remove/path': '/path' // remove base path
}*/
}));
app.listen(port);
5、proxy()将不同接口地址代理到不同目标地址,用法:
const express = require('express');
const proxy = require('http-proxy-middleware');
const app = express();
app.use(
['/api/login', '/api/user/*', '/api/drag/*'],
proxy({
target: 'http://127.0.0.1:8800',
changeOrigin: true
// ws: true
/* pathRewrite: {
'^/api/old-path': '/api/new-path', // rewrite path
'^/api/remove/path': '/path' // remove base path
}*/
}));
app.use(
['/api/mock/*'],
proxy({
target: 'http://127.0.0.1:8000',
changeOrigin: true
// ws: true
// pathRewrite: {
// '^/api/old-path': '/api/new-path', // rewrite path
// '^/api/remove/path': '/path' // remove base path
// }
}));
app.listen(port);
参考文档:
https://www.npmjs.com/package/http-proxy-middleware
自己随笔总结,不喜勿喷,谢谢。