Created
December 4, 2018 11:56
-
-
Save BryanYang/a22e5ce413615ad3941ff0af6d612b3d to your computer and use it in GitHub Desktop.
koa2 http-proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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