【问题标题】:Sending response to client from within the request.post callback in koa从 koa 的 request.post 回调中向客户端发送响应
【发布时间】:2016-06-30 10:47:25
【问题描述】:

我有这条 koa 路线 /landing 导致 404。

function* landing() {
    //this.body = "response"; //1
    var request = require('request');
    request.post('http://url.com/resource',
    { json: { key: "post data"} },
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var token = body.data;
            getListByToken(token, function(list){
                this.body = list; //2
            });
        }
    });
}

请参阅顶部//1 中的评论 - 这就是您在路由中定义 koa 响应正文的方式。而不是//1 我想从//2 发送响应,即从该request.get 中发送。

当用户被路由到/landing 时,post 请求必须从 url 获取一些数据。 getListByToken 将使用获取的数据来带来一些其他数据,list,这些数据应该发送给用户。上面的代码应该可以工作,但它会导致 koa 的 404 Not Found 响应。

【问题讨论】:

    标签: node.js routes koa


    【解决方案1】:

    我们可以使用promise,简单干净的方式来管理异步代码。

    var request = require('request-promise');
    
    . . .
    
    function* landing() {
      try {
        let response = yield request( {
          method: 'POST',,
          url: 'http://url.com/resource',
          headers: { 'content-type': 'application/json' },
          body: JSON.stringify( { json: { key: "post data"} } )
        } );
    
        this.body = yield new Promise( function( resolve, reject ) {
          if ( response.statusCode == 200 ) {
            getListByToken( response.body.token, function( list ) {
              resolve( list );
            } );
          }
        } );
      } catch ( err ) {
        /* do something with your errors */
      }
    }
    

    【讨论】:

      【解决方案2】:

      q 解决了这个问题。它使 koa 保持响应,直到 yield 发生。

      var q = require('q');
      function* landing() {
          var deferred = q.defer();
          var request = require('request');
          request.post('http://url.com/resource',
          { json: { key: "post data"} },
          function (error, response, body) {
              if (!error && response.statusCode == 200) {
                  var token = body.data;
                  getListByToken(token, function(list){
                      deferred.resolve(repolist);
                  });
             }
          });
          this.body = yield deferred.promise;
      }
      

      感谢https://stackoverflow.com/a/22159513/1128379

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-11
        • 2013-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多