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

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

本文介绍了如何使用Koa路由器复制和转发请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For several reasons, I have a server that has to forward requests to another server. The response should be the response of the final server. I also need to add an extra header onto the request but remove this header again from the response before returning. As such, redirect isn't going to cut it.

我目前正在手动复制标头&正文,但我想知道是否有一种简单的通用方法?

I'm currently doing it manually copying the headers & body as required but I would like to know if there's a simple generic way to do it?

推荐答案

为此可以使用代理.假设@ koa/router或类似的东西以及http-proxy模块(还有一些适用于Koa的包装器模块,

A proxy would work for this. Assuming @koa/router or something simliar and the http-proxy module (there are also wrapper modules for Koa that may work:

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服务器,也可以将代理从路由中移出:

You could also lift the proxy out of a route if you happen to be starting your Koa server with http.createServer rather than app.listen:

// 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)
})

这篇关于如何使用Koa路由器复制和转发请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 05:08