Javascript node.js 请求对象-返回响应体以供进一步操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28268873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
node.js request object- return response body for further operation
提问by Glenn Dekhayser
There's probably an easy answer for this, but I'm trying to get the body of the response back and returned to another function. It's certainly a scope problem.
对此可能有一个简单的答案,但我正在尝试返回响应正文并返回到另一个函数。这当然是一个范围问题。
Here's my code, any ideas would be most appreciated:
这是我的代码,任何想法将不胜感激:
var request = require("request");
var myJSON = require("JSON");
function getMyBody(url) {
var myBody;
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
myBody = body;
}
});
return(JSON.parse(myBody));
}
}
js_traverse(getMyBody(url));
Thanks
谢谢
Glenn
格伦
回答by Ben
The statement:
该声明:
return(JSON.parse(myBody));
Get executed before the ajax call returns you the body. You need to pass in the callback to getMyBody() to do something with what the body of request() returns:
在 ajax 调用返回正文之前执行。您需要将回调传递给 getMyBody() 以处理 request() 的主体返回的内容:
var request = require("request");
var myJSON = require("JSON");
function getMyBody(url, callback) {
request({
url: url,
json: true
}, function (error, response, body) {
if (error || response.statusCode !== 200) {
return callback(error || {statusCode: response.statusCode});
}
callback(null, JSON.parse(body));
});
}
getMyBody(url, function(err, body) {
if (err) {
console.log(err);
} else {
js_traverse(body);
}
});

