【发布时间】:2015-06-18 03:18:56
【问题描述】:
我是 NodeJS 的新手,但我环顾四周,似乎无法在下面找到解决问题的方法。我确信这很简单,但提前感谢您提供的所有帮助!
我正在尝试通过 NodeJS 制作一个简单的 JSON 抓取工具。我所需要的只是将 JSON 存储到一个变量中。问题是,我正在使用 Require,他们的示例只是将其记录到控制台。我已经尝试在它登录到控制台后添加一个变量,但我只是变得不确定。下面是我的代码,到目前为止它非常简单:)
// var jsonVariable; Doesn't work, shown as a test
function getJSON(url){
var request = require("request")
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body) // Print the json response
//return body; This doesn't work, nor does making a global variable called json and assigning it here. Any ideas?
//jsonVariable = body; // This also doesn't work, returning undefined even after I've called the function with valid JSON
}
})
}
再次感谢您给我的任何帮助:)
【问题讨论】:
-
当您
return body时,您将其返回到function (error, response, body)回调,而不是实际返回到getJSON函数 -
我不明白,json 是在一个变量中,
body。如果您在其他地方需要,请添加回调。 -
jsonVariable = body有效。但它是在您调用该函数后的某个时间设置的。为了证明它有效,在将来的某个时间使用setTimeout检查jsonVariable的值。这意味着你永远,永远,永远,永远(我怎么强调都不为过),永远从异步函数返回一个值。相反,您需要做的是将回调传递给 receive 值。
标签: javascript json node.js require