Reputation: 80
I tried to get weather API data from this program,my problem is that this program's output is undefined,I expected an object,Why the output is undefined and how I can get the required object?
const url = "https://api.weatherapi.com/v1/current.json?key=KEYREDACTED&q=London"
const url1 = "https://api.openweathermap.org/data/2.5/weather?q=New Delhi,India&appid=KEYREDACTED"
const apiRequest = https.get(url,(res) => {
let data ="";
res.on("data",(chunk) => {
data+=chunk;
JSON.parse(data);
})
res.on("end",() => {
console.log(data.location);
});
});
Upvotes: 0
Views: 2386
Reputation: 1
I just would like to add to the ffritz response which is correct and say that there are npm packages that will cut your work in half or just use pure ES6 and fetch which is also super simple and makes all that conversion work for you.
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(data => console.log(data));
Here is some documentation.
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Upvotes: 0
Reputation: 2261
Important: Never include API Keys/IDs in your question (the part after ?key=
and &appid=
). Other people can use them and use up your traffic.
You are parsing data using JSON.parse
while the response is still being received. Move that to the "end"
part.
https.get(url,(res) => {
let data ="";
res.on("data",(chunk) => {
// Data is being received in chunks, we add it to the data variable to save it
data+=chunk;
})
res.on("end",() => {
// all data has been received, now we can parse it and are done
const parsedData = JSON.parse(data);
console.log(parsedData);
});
});
The parsedData
is probably the object you are looking for.
Upvotes: 1