Skip to content

Instantly share code, notes, and snippets.

@BryanYang
Created December 4, 2018 11:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BryanYang/a22e5ce413615ad3941ff0af6d612b3d to your computer and use it in GitHub Desktop.
Save BryanYang/a22e5ce413615ad3941ff0af6d612b3d to your computer and use it in GitHub Desktop.
koa2 http-proxy
import Koa from 'koa';
const mnsUtil = require('@mtfe/mns-util');
const httpProxy = require('http-proxy');
import config = require('config');
const proxy = httpProxy.createProxyServer({
headers: {
Host: 'alitest.e.fanxiaojian.cn',
},
});
mnsUtil.getSwimlane().then((swimlane: {}) => {
config.swimlane = swimlane;
});
// 代理的路径
const pxPaths = [
'/hq-agency',
'/crm-api',
'/irs-api',
'/metis-login-web',
'/org-web',
'/component-web',
'/account-web',
];
// 是否走代理
const isPxPath = (path: string) => pxPaths.some(p => path.startsWith(p));
const proxy2px = (): Koa.Middleware => {
return async (ctx, next) => {
if (
mnsUtil.getLocalOctoEnv() === 'test' &&
isPxPath(ctx.request.path) &&
config.swimlane
) {
await new Promise((resolve, reject) => {
ctx.res.on('close', () => {
reject(new Error('http response closed'));
});
ctx.res.on('finish', () => {
resolve();
});
proxy.web(ctx.req, ctx.res, {
target: 'http://alitest.e.fanxiaojian.cn',
});
});
} else {
await next();
}
};
};
export default proxy2px;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment