Egg: 如果我需要加一个路由把数据从网页端代理到第三方服务端,这个如何实现?

Created on 20 Feb 2017  ·  6Comments  ·  Source: eggjs/egg

比如:我在页面上传一个文件,但我需要直接把文件数据流代理到第三方服务器上面,代理过程中可能我要对headers或者其他的做一些处理或者包装,因此就没有直接用nginx直接代理转发,请问一下我需要怎么处理? 还有下载文件代理?

question

Most helpful comment

@fengxinming 你如果对 http 的协议有一定理解的话,可以自己基于 egg 提供的功能来实现你要的需求,简单的来说就是:

  1. 如果你有一些 JSON、FORM 接口要转发的话,需要关闭 bodyparser 对 body 的默认解析
  2. 通过 httpclient 来转发请求,其中会涉及到一些 stream 的处理
// config/config.default.js

exports.bodyParser = {
  ignore: '/proxy', // 配置对 /proxy 路径请求不解析 body
};
// app/router.js
app.get('/proxy', 'proxy.index');
// app/controller/proxy.js

module.exports = app => {
  return class ProxyController extends app.Controller {
    * index() {
      const { ctx } = this;
      const headers = processHeader(ctx.headers);
      const result = yield this.curl(target, {
        streaming: true, // 流式获取响应
        stream: this.req, // 将原始请求的 body 转发给 target
      });
      ctx.body = result.res; // 将 target 的响应直接赋值给 body
    }
  }
}

All 6 comments

@fengxinming 你如果对 http 的协议有一定理解的话,可以自己基于 egg 提供的功能来实现你要的需求,简单的来说就是:

  1. 如果你有一些 JSON、FORM 接口要转发的话,需要关闭 bodyparser 对 body 的默认解析
  2. 通过 httpclient 来转发请求,其中会涉及到一些 stream 的处理
// config/config.default.js

exports.bodyParser = {
  ignore: '/proxy', // 配置对 /proxy 路径请求不解析 body
};
// app/router.js
app.get('/proxy', 'proxy.index');
// app/controller/proxy.js

module.exports = app => {
  return class ProxyController extends app.Controller {
    * index() {
      const { ctx } = this;
      const headers = processHeader(ctx.headers);
      const result = yield this.curl(target, {
        streaming: true, // 流式获取响应
        stream: this.req, // 将原始请求的 body 转发给 target
      });
      ctx.body = result.res; // 将 target 的响应直接赋值给 body
    }
  }
}

@atian25 别用这个,我还没改过

@popomore 有什么 bug 么?

@atian25 用的 request,还没重构过。

这个先关了, 有兴趣的同学可以用自带的 httpclient 封装个 egg-httpproxy, 参考上面 koa-proxy 的源码和死马的示例.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

skyyangpeng picture skyyangpeng  ·  3Comments

Webjiacheng picture Webjiacheng  ·  3Comments

Leungkingman picture Leungkingman  ·  3Comments

whlsxl picture whlsxl  ·  3Comments

zhaofinger picture zhaofinger  ·  3Comments