问题
I have the following code:
getWeather = e => {
e.preventDefault();
const api_call = fetch(
`http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=${API_KEY}`
);
const data = api_call.json();
console.log(data);
};
But I keep getting .json() is not a function. Not sure why I am getting that.
回答1:
That's because you didn't wait for the request to end.
Try this instead:
const api_call = fetch(
`http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=${API_KEY}`
).then(res => res.json()).then(console.log);
回答2:
Fetch returns a promise, so in your case you would want to use async/await
:
getWeather = async e => {
e.preventDefault();
const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=${API_KEY}`);
const data = api_call.json();
console.log(data);
};
Or you could use .then()
and .catch()
blocks:
getWeather = e => {
e.preventDefault();
fetch(`http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=${API_KEY}`)
.then(res => res.json())
.then(res => {
console.log(res)
})
.catch(err => console.log(err))
};
回答3:
Use await on fetch (returns a Promise)
getWeather = async e => {
e.preventDefault();
const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=${API_KEY}`);
const data = api_call.json();
console.log(data);
};
回答4:
Put await
before fetch
and make the function async
getWeather = async e => {
e.preventDefault();
const api_call = await fetch(
`http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=${API_KEY}`
);
const data = api_call.json();
console.log(data);
};
来源:https://stackoverflow.com/questions/60839014/data-json-is-not-a-function-react