2015-11-06 148 views
1

我在节点js服务器上有一个REST API。当它收到一个GET请求时,它将调用一个将调用另一个服务器get函数的函数。代码如下所示:处理异步http调用节点js

var server = http.createServer(function(request, response) { 
    console.log("YEAHHH! ", request.method); 
    var string=''; 
    // Inside a request handler method 
    if (request.method == "OPTIONS") { 
     console.log("options"); 
     // Add headers to response and send 
     //response.writeHead(statusCode, responseHeaders); 
     response.writeHead(success,responseHeaders); 
     response.end(); 
    } 
    if(request.method == "GET") { 
     string = soso(); 
    } 

    console.log("*******", string); 
    response.writeHead(success,responseHeaders); 
    response.end(string); 
}); 

soso()是对其他服务器的调用。问题是我想在它完成之前发送soso()函数的响应,所以我得到的是一个空字符串。

我该如何解决这个问题?

我相信这是一个重复,但不能完全找到我在找什么。所以,任何帮助表示赞赏。

编辑

代码为索索功能:

var soso = function() { 
    console.log("this is being called"); 
    var options = {...} 

    var req = https.get(options, function(res) { 
     var str = ''; 
     res.on('data', function (chunk) { 
      str += chunk; 
     }) 

     res.on('end', function() { 
      console.log ("str is: ", str); 
      string = str; 
     }) 

     req.end(); 
     console.log(res.statusCode); 
     console.log(responseHeaders); 
    }); 

} 
+0

哪里了'索索()'的代码? – jfriend00

+0

看来你要做的是为其他服务器做一个代理。有很多很多已有的代码可以做到这一点。 – jfriend00

+0

@ jfriend000个人最爱的任何链接? – discodane

回答

0

你可以尝试这样的事情,我不知道。我没有测试过这个。在soso函数中传递响应对象,然后在获取请求结束后使用response.end(string);

var server = http.createServer(function(request, response) { 
     console.log("YEAHHH! ", request.method); 
     var string=''; 
     // Inside a request handler method 
     if (request.method == "OPTIONS") { 
      console.log("options"); 
      // Add headers to response and send 
      //response.writeHead(statusCode, responseHeaders); 
      response.writeHead(success,responseHeaders); 
      response.end(); 
     } 
     if(request.method == "GET") { 
      string = soso(response); //send response object as argument 
     } else { 
    console.log("*******", string); 
     response.writeHead(success,responseHeaders); 
     response.end(string); 
    } 


    }); 

索索功能

var soso = fuction(response){ // we pass the response object in soso function 
    console.log("this is being called"); 
     var options = {...} 

     var req = https.get(options, function(res) { 
      var str = ''; 
      res.on('data', function (chunk) { 
       str += chunk; 
      }) 

      res.on('end', function() { 
       console.log ("str is: ", str); 
       string = str; 
      }) 

      req.end(); 
    response.writeHead(success,responseHeaders); 
     response.end(string); 
      console.log(res.statusCode); 
      console.log(responseHeaders); 
     }); 

}