如何处理异步/等待获取API中的错误404

时间:2018-08-10 07:22:59

标签: javascript reactjs async-await 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);
  }
<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>

Error from Browser

4 个答案:

答案 0 :(得分:4)

在尝试使用status方法提取正文之前,只需检查已解决承诺的.json()属性。

async function test() {
  const api_call = await fetch(`https://cors-anywhere.herokuapp.com/http://example.com/fake/fake`);
  console.log(api_call.status);
}

test();

答案 1 :(得分:1)

尝试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);  
    }
}

答案 2 :(得分:1)

使用

class App extends React.Component{
  getWeather = async (e) => {
    e.preventDefault();

    const city = e.target.elements.city.value;
    const country = e.target.elements.country.value;
    try {
        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(e);
    }

  }

答案 3 :(得分:0)

无论使用var Avals = ss.getRange("A1:A").getValues(); var Alast = Avals.filter(function(r){return r[0].length>0});还是诺言链,async/await API都会返回一个包含fetch对象的promise。响应对象包含一个Response属性,该属性返回HTTP状态代码。在status对象上调用.json()方法之前,可以检查一下response。例如,对于成功的请求,OpenWeather API将返回HTTP状态代码if res.status === 200。因此,要检查您的API请求是否成功,可以执行以下操作...

200

您可以看到更多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(); } } 对象的属性和方法By viewing the MDN documentation