我在 Node js 服务器上有一个 RESTish api。当它收到一个 GET 请求时,它会调用一个函数,然后该函数将调用另一个服务器的 get 函数。代码如下所示:
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);
});
}
最佳答案
你可以尝试这样的事情,我不确定。我没有测试过这个。在soso函数中传入response对象,get请求结束后使用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);
});
}
关于node.js - 处理异步http调用 Node js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33560089/