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

问题描述

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

我目前正在根据需要手动复制标题和正文,但我想知道是否有简单的通用方法来做到这一点?

解决方法

代理可以解决这个问题。假设 @koa/router 或类似的东西和 http-proxy 模块(也有可能工作的 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,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,options)
  }

  return handler(req,res)
})