【发布时间】:2016-02-07 04:54:22
【问题描述】:
我在节点 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() 函数完成之前发送它的响应,所以我得到的只是一个空字符串。
我该如何解决这个问题?
我确定这是重复的,但无法完全找到我要查找的内容。因此,任何帮助表示赞赏。
编辑
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()的代码在哪里? -
看来您正在尝试为其他服务器创建代理。有很多很多预先存在的代码可以做到这一点。
-
@jfriend000 有个人收藏的链接吗?
-
我自己没用过,但这个看起来很有希望:github.com/nodejitsu/node-http-proxy。或者,您可以单独使用 nginx。
标签: node.js http asynchronous