Koa http-proxy 反向代理设置

07-19
评论
字数统计:777(字)
使用koa做代理服务器,实现不同域名请求同一台服务器代理至不同的服务,主要使用到http-proxy。
const proxy = require('http-proxy').createProxyServer();
// 拦截所有请求,匹配跳转
router.all('/(.*)', async ctx => {
  switch (ctx.request.hostname) {
    case 'domain.com':
      // 很关键的一步,需要关闭默认的response行为才能正常跳转。
      ctx.respond = false;
      proxy.web(ctx.req, ctx.res, {
        target: {
          host: 'localhost',
          port: 5500
        }
      });
      return;
    default:
      ctx.set('Content-Type', 'text/html');
      ctx.body = fs.readFileSync(path.join(__dirname, 'html', '404', 'index.html'));
      return;
  }
});

ctx.respond官方描述:为了绕过 Koa 的内置 response 处理,你可以显式设置 ctx.respond = false;。 如果您想要写入原始的 res 对象而不是让 Koa 处理你的 response,请使用此参数。


本文链接:https://blog.crazylei.com/art/7be362ca
版权声明: 本博客所有文章除特别声明外,均采用CC BY 4.0 CN协议 许可协议。转载请注明出处!

评论

正在加载评论...

友情链接:互链8收录网
©2022 Crazylei Bolg沪ICP备20001821号