0
我正在使用Node.js
创建天气应用程序来访问当前天气。如何在Javascript中使用闭包访问变量
当我调用openweatherapp API,通过我试图传递给module.exports
的JSON检索到的温度可变嵌套一系列闭合的功能之内。
有什么办法可以让我访问temperature
并通过module.exports
,这样我就可以从另一个文件中检索数据了吗?
var http = require('http')
const apiKey = "myAPIkey"
// Connect to API URL api.openweathermap.org/data/2.5/weather?q={city name}
function accessWeather(city, callback) {
var options = {
host: "api.openweathermap.org",
path: "/data/2.5/weather?q=" + city + "&appid=" + apiKey + "",
method: "GET"
}
var body = ""
var request = http.request(options, function(response) {
response.on('data', function(chunk) {
body += chunk.toString('utf8')
})
response.on('end', function() {
var json = JSON.parse(body)
var temperature = parseInt(json["main"]["temp"] - 273)
})
})
request.end()
}
temp = accessWeather("Calgary")
console.log(temp)
module.exports = {
accessWeather: accessWeather
}