【问题标题】:multiple http get request node.js多个http获取请求node.js
【发布时间】:2015-02-10 23:59:45
【问题描述】:

这就是我的代码对于单个 http get 请求的样子。我想要做的是再调用两个 http get 请求并存储它们的结果,以便我可以适当地渲染。谁能建议我如何实现它?谢谢

router.get('/get_all_posts', function(req, res){
        var body ='';

        var options = {
            host: 'localhost',
            path: '/some_endpoint',
            method: 'GET',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        };


        var request = http.request(options, function(response) {
            response.setEncoding('utf8');

            response.on('data', function (data_chunk) {
                body += data_chunk;
            });

            response.on('end', function () {

                if(response) {
                    res.render("something");
                }
                else
                {
                    res.render('error', {error: {status:400,stack:body}});
                }

            });
        });
        request.end();
    });

【问题讨论】:

    标签: node.js asynchronous


    【解决方案1】:

    您不应该发出 http 请求。无论您为/some_endpoint 提供什么代码,都将其转换为一个函数,然后在路由器内部为/some_endpoint/get_all_posts 调用该函数。

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      这对我有用。

      async.map([options1, options2, options3], reqCall, function(err, results){
                  if ( err){
                      // do something
                  } else {
                         results[0]//first call
                         results[1]//second call
                         results[2] //third call
                 }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-29
        • 2013-10-02
        • 1970-01-01
        • 1970-01-01
        • 2016-04-02
        • 1970-01-01
        • 1970-01-01
        • 2013-06-12
        相关资源
        最近更新 更多