首页 > 解决方案 > 使用 openweather API 和 ReactJS 处理错误 404

问题描述

我正在创建一个非常简单的应用程序,它显示世界城市的温度。

api 返回时出现错误 404 not found

我想处理错误 404 并显示一条类似You have to introduce a valid city name.

我尝试将以下内容放在search函数内部(最后)但无法正常工作:

if (weather.cod){
   console.log("Erroooor");
}

这是我的完整代码:

import React, { useState } from 'react';

const api = {
  key: "0e128f999e1fb1174d7af1d207406c01",
  base: "https://api.openweathermap.org/data/2.5/"
}

function App() {

  const [query, setQuery] = useState('');
  const [weather, setWeather] = useState({});

  const search = evt => {
    if (evt.key === 'Enter') {
      fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
        .then(res => res.json())
        .then(result => {
            setWeather(result);
            setQuery('');
        });
    }
  }

  const dateBuilder = (d) => {
    let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; 
    
    let day = days[d.getDay()];
    let date = d.getDate();
    let month = months[d.getMonth()];
    let year = [d.getFullYear()];

    return `${day} ${date} ${month} ${year}`;
  }

  return (

    <div className={(typeof weather.main != "undefined")
      ? ((weather.main.temp > 20)
      ? 'app warm' : 'app cold') : 'app'}>
      <main>
        <div className="search-box">
          <input
            type="text"
            className="search-bar search-focus"
            placeholder="Type a city ..."
            onChange={e => setQuery(e.target.value)}
            value={query}
            onKeyPress={search}
          />
        </div>

        {(typeof weather.main != "undefined") ? (
          <div>
            <div className="location-box">
              <div className="location">{weather.name}, {weather.sys.country}</div>
              <div className="date">{dateBuilder(new Date())}</div>
            </div>
            <div className="weather-box">
              <div className="temp">
                {Math.round(weather.main.temp)}ºC
              </div>
              <div className="weather">
                {weather.weather[0].description}
              </div>
            </div>
          </div>
        ) : ('')}
      </main>
    </div>
  );
}

export default App;

标签: reactjsopenweathermap

解决方案


您可以添加 useState 来处理错误

添加

const [notFoundError,setNotFoundError]= useState(false)

作为回报,您可以添加 if 检查以检查错误是否为真

const App = ()=>{
const [notFoundError,setNotFoundError]= useState(false)
const [weather, setWeather] = useState({});

  const search = evt => {
    if (evt.key === 'Enter') {
      fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
        .then(res => res.json())
        .then(result => {
            // check if the API return the status 
            if(resuit.code == 404){
                  setNotFoundError(true)
            }else{
            // other status like 200
            
            setWeather(result);
            setQuery('');
            }
        });
    }
  }

return(
      notFoundError ? <h1>You have to introduce a valid city name</h1> :(
      <div> in case there is no error you can output the weather information </div>)
      );
}

警告:请删除并更改您的 API 密钥,因为它是私有的,任何人都可以使用此密钥,您不应该在互联网上共享它


推荐阅读