npm install --save-dev koa2-proxy-middleware
const Koa = require('koa');
const proxy = require('koa2-proxy-middleware');
const bodyparser = require('koa-bodyparser');
const app = new Koa();
const options = {
targets: {
'/user': {
// this is option of http-proxy-middleware
target: 'http://localhost:3000', // target host
changeOrigin: true, // needed for virtual hosted sites
},
'/user/:id': {
target: 'http://localhost:3001',
changeOrigin: true,
},
// (.*) means anything
'/api/(.*)': {
target: 'http://10.94.123.123:1234',
changeOrigin: true,
pathRewrite: {
'/passager/xx': '/mPassenger/ee', // rewrite path
}
},
// ws
'/websocket': {
target: 'ws://10.94.123.123:6789',
ws: true,
changeOrigin: true
}
}
}
app.use(proxy(options));
app.use(bodyparser({
enableTypes:['json', 'form', 'text']
}));
http-proxy-middleware文档: https://www.npmjs.com/package/http-proxy-middleware
koa2-proxy-middleware文档: https://www.npmjs.com/package/koa2-proxy-middleware
const path = require('path');
const Koa = require('koa');
const app = new Koa();
const serve = require('koa-static');
const proxy = require('koa2-proxy-middleware');
const bodyparser = require('koa-bodyparser');
// 配置静态服务
const index = serve(path.join(__dirname) + '/dist/'); // 静态文件目录
app.use(index);
// 配置代理
const options = {
targets: {
'/api/(.*)': {
target: 'http://127.0.0.1:8000',
ws: true,
changeOrigin: true, // 是否跨域
pathRewrite: {
'/api': '', // 重写路径
},
},
},
};
app.use(proxy(options));
app.use(
bodyparser({
enableTypes: ['json', 'form', 'text'],
})
);
const hostName = 127.0.0.1;
const port = 8888;
app.listen(port, hostName, () => {
console.log(`服务运行在http://${hostName}:${port}`);
});
console.log('成功启动');