【问题标题】:nodejs pipe http response to koa resnodejs管道http响应到koa res
【发布时间】:2016-07-26 05:52:25
【问题描述】:

我正在使用 koa , 当某些条件满足时,如何将用户的请求发送到另一台服务器,然后从服务器获得响应并将其发送给用户,就好像我是代理服务器一样。 我使用 http.request 并获得了 res ,现在我如何将 res 传输到用户的套接字,就像原始的 http 服务器 res.pipe(response)

例如

var options = {
      host: "blog.suconghou.cn",
      port: 80,
      encoding: null,
      path: "http://blog.suconghou.cn",
      headers: {
        Host: "blog.suconghou.cn"
      }
    };

    http.request(options, function(res)
    {
        res.pipe(process.stdout);
        console.log(res.body,typeof res);
        ctx.body=res; // ctx is this in app.use
    }).end();

它不起作用,我不知道如何将它传递给 koa 的响应

【问题讨论】:

  • 想法:将 http.request 包装在一个返回带有resolve(res) 的承诺的函数中。从路线,尝试ctx.body = yield makeRequest(...)。您的代码的一个问题是您的 koa 处理程序在请求回调完成之前返回。你需要等待它。
  • @danneu 好的,我知道,但是我怎样才能使用像 github.com/koajs/koa/blob/master/lib/application.js#L227 这样的管道,这样我就不需要对标题做很多事情了

标签: node.js http koa


【解决方案1】:

request库支持流,使用它你可以做如下。

let request = require('request');

function *mid() {
    let options = {
        host: "blog.suconghou.cn",
        port: 80,
        encoding: null,
        path: "http://blog.suconghou.cn",
        headers: {
            Host: "blog.suconghou.cn"
        }
    };

    this.req.pipe(request(options))
            .pipe(this);
            .once('error', console.log);
}

【讨论】:

    猜你喜欢
    • 2014-09-21
    • 1970-01-01
    • 2017-09-09
    • 2021-06-24
    • 1970-01-01
    • 2018-02-07
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多