gpt4 book ai didi

javascript - 从nodejs中的http请求获取值

转载 作者:太空宇宙 更新时间:2023-11-04 03:02:46 25 4
gpt4 key购买 nike

var latLon = "40.8,-77.8"; //Lat/lon
var cityCode = ""; //City code
var cityName = "";
var latLongCityCodeURL = ("http://dataservice.accuweather.com/locations/v1/cities/geoposition/search?apikey=" + weatherKey + "&q=" + latLon);

//Current Conditions Vars
var ccWeatherText = ""; //Text for weather at location
var ccTemp = 0; //Degrees Farenheit
var ccIcon = 0; //weather icon number https://developer.accuweather.com/weather-icons
var ccURL = "test"; //URL for get
//12 hour forecast Conditions Vars


//5 day forecast conditions Vars

//Get city code
http.get(latLongCityCodeURL, (resp) => {
var that = this;
resp.on("data", (chunk) => {
var result = JSON.parse(chunk);
var cityCode = result.Key;
var cityName = result.EnglishName;
console.log(cityCode + " " + cityName);
that.cityName = cityName;
that.cityCode = cityCode;
});

}).on("error", (err) => {
console.log("Error: " + err.message);
});


console.log(cityCode + " " + cityName);

所以我的问题是,我正在使用 require('http') 发出 http 请求,我想要做的是解析数据并将其存储在我的全局变量中,以便我可以将它们用于其他请求。我尝试过使用 var that=this 并且尝试将全局变量分配给数据。我不知道该怎么做,我只是一直没有定义。我知道它与 ASYNC 有关,也与范围有关。请帮忙

最佳答案

您可以将结果保存到不同范围级别的变量中。请记住,Node.js 中的大多数 i/o 调用都是异步的。这是一个例子:

var latLon = "40.8,-77.8"; //Lat/lon
var cityCode = ""; //City code
var cityName = "";
var latLongCityCodeURL = ("http://dataservice.accuweather.com/locations/v1/cities/geoposition/search?apikey=" + weatherKey + "&q=" + latLon);

//Current Conditions Vars
var ccWeatherText = ""; //Text for weather at location
var ccTemp = 0; //Degrees Farenheit
var ccIcon = 0; //weather icon number https://developer.accuweather.com/weather-icons
var ccURL = "test"; //URL for get


var savedResult = null;

//Get city code
http.get(latLongCityCodeURL, (resp) => {
var jsonData = '';
resp.on("data", (chunk) => {
jsonData += chunk;
});
resp.on("end", () => {
savedResult = JSON.parse(jsonData);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});


// Display saved result once available.
setTimeout(displaySavedResult, 2000);

function displaySavedResult() {
if (!savedResult) {
console.log('Last result is null!');
} else {
console.log('Last result: City Code: ' + savedResult.Key + " Name" + savedResult.EnglishName);
console.log('Last result (all properties): ', JSON.stringify(savedResult, null, 2));
}
}

关于javascript - 从nodejs中的http请求获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50363539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com