Pau*_*aul 5 javascript async-await reactjs fetch-api
如果没有数据,有没有发现错误的机会?我收到错误404,但无法通过console.log例如...
class App extends React.Component{
getWeather = async (e) => {
e.preventDefault();
const city = e.target.elements.city.value;
const country = e.target.elements.country.value;
const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${API_KEY}&units=metric`);
const data = await api_call.json();
console.log(data);
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Run Code Online (Sandbox Code Playgroud)
无论使用async/await
还是 Promise 链,fetch
API 都会返回一个promise
包含Response
对象。响应对象包含status
一个返回 HTTP 状态代码的属性。在调用对象.json()
的方法之前response
,您可以检查一下if res.status === 200
。例如,OpenWeather API 将返回200
成功请求的 HTTP 状态代码。因此,要检查您的 API 请求是否成功,您可以执行以下操作...
class App extends React.Component{
getWeather = async (e) => {
e.preventDefault();
const city = e.target.elements.city.value;
const country = e.target.elements.country.value;
const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${API_KEY}&units=metric`);
if (api_call.status !== 200) {
// You can do your error handling here
} else {
// Call the .json() method on your response to get your JSON data
const data = await api_call.json();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过查看 MDN 文档来查看更多Response
对象属性和方法
尝试try catch
:
getWeather = async (e) => {
try {
e.preventDefault();
const city = e.target.elements.city.value;
const country = e.target.elements.country.value;
const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${API_KEY}&units=metric`);
const data = await api_call.json();
console.log(data);
} catch(e) {
console.log('error: ', e);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2239 次 |
最近记录: |