如何使用koa路由器复制和转发请求



由于几个原因,我有一个服务器必须将请求转发到另一个服务器。响应应该是最终服务器的响应。我还需要在请求中添加一个额外的头,但在返回之前再次从响应中删除这个头。因此,重定向不会削减它。

我目前正在手动复制头&身体,但我想知道是否有一个简单的通用方法来做到这一点?

一个代理可以实现这一点。假设@koa/router或类似的东西和http代理模块(koa的包装器模块也可以工作:

const proxy = httpProxy.createProxyServer({
target: 'https://some-other-server.com',
// other options, see https://www.npmjs.com/package/http-proxy
})
proxy.on('proxyReq', (proxyReq, req, res, options) => {
proxyReq.setHeader('x-foo', 'bar')
})
proxy.on('proxyRes', (proxyRes, req, res) => {
proxyRes.removeHeader('x-foo')
})
router.get('/foo', async (ctx) => {
// ctx.req and ctx.res are the Node req and res, not Koa objects
proxy.web(ctx.req, ctx.res, {
// other options, see docs
})
})

如果您碰巧用http.createServer而不是app.listen:启动Koa服务器,您也可以将代理从路由中移除

// where app = new Koa()
const handler = app.callback()
http.createServer((req, res) => {
if (req.url === '/foo') {
return proxy.web(req, res, options)
}
return handler(req, res)
})

最新更新