Using the accuweather API I need to get the code of a city before getting the weather of that city. As the screenshot shows the location array is empty. The program still goes into the branch that expects an array that is not empty.
router.get("/weather/currentweather/:location", async (req, res) => {
try {
const optionsForLocation = {
uri: `http://dataservice.accuweather.com/locations/v1/cities/autocomplete?apikey=${config.get(
"accuWeatherAPIKey"
)}&q=${req.params.location}&language=en-us`,
method: "GET",
headers: { "user-agent": "node.js" }
};
rp(optionsForLocation, (error, response, body) => {
if (error) {
//console.error(error);
//res.status(500).send("Server Error");
res.json({ weather: "No Location found" });
}
console.log(response.body); // Returns []
if (response.body === []) {
//res.status(404).json({ msg: "No location found" });
res.json({ weather: "No Location found" });
//break;
}
}).then(function(locations) {
console.log(locations); // Returns []
if (locations === []) {
res.json({ weather: "No Location found" });
} else { // Still takes this path although locations === []
const locationsJSON = JSON.parse(locations);
console.log(locationsJSON);
const key = locationsJSON[0].Key; //Always throws an error here as locationsJSON is empty if no location was found. This path should not be taken in the first place if locations === []
const optionsForCurrentConditions = {
uri: `http://dataservice.accuweather.com/currentconditions/v1/${key}?apikey=${config.get(
"accuWeatherAPIKey"
)}`,
method: "GET",
headers: { "user-agent": "node.js" }
};
request(optionsForCurrentConditions, (error, response, body) => {
if (error) {
console.error(error);
res.status(500).send("Server Error");
}
if (response.statusCode !== 200) {
return res.status(404).json({ msg: "No current conditions found" });
}
res.json(JSON.parse(body));
});
}
});
} catch (error) {
console.error(err.message);
res.status(500).send("Server Error");
}
});
I fiddled with it for hours now, but can't get this error to get away.
Thanks for your help!