【问题标题】:Handle error 404 using openweather API and ReactJS使用 openweather API 和 ReactJS 处理错误 404
【发布时间】:2021-07-04 18:47:18
【问题描述】:

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

当 api 返回 not found 时出现错误 404。

我想处理错误 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;

【问题讨论】:

  • 你真的不应该在互联网上发布 API 密钥。
  • 如果 res.status === 404 可能尝试/捕获并抛出带有该消息的新错误?
  • @sloont 哦,别担心,是测试项目,API我不关心。不过谢谢!
  • 任何人使用该密钥所做的任何事情都可能与生成该密钥的人相关联。我知道你说它只是一个测试项目,但如果有人对它进行恶意操作,它仍然是他们用来执行此操作的密钥。

标签: reactjs openweathermap


【解决方案1】:

编辑我认为你必须尝试/赶上。所以在try/catch 中做async/await 看起来会更干净。这是一个相关的SO post。见第一个答案。 我对 jQuery 不是很好,所以如果有任何需要改变,我也无能为力,但我认为不会。当你得到一个 404 时,你可以抛出一个自定义的 Error 对象。

类似:

  const search = evt => {
    if (evt.key === 'Enter') {
      fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
        .then(res => {
           if (res.status === 404) {
             const error = new Error();
             error.message = 'You have to introduce a valid city name';
             throw error;
           }
        })
        .then(res => res.json())
        .then(result => {
            setWeather(result);
            setQuery('');
        })
        .catch(error => console.log(error.message));
        
    }
  }

【讨论】:

  • 你的代码有可能在语法上是错误的吗? Declaration or statement expected.ts(1128) 正好在.then 2 号:.then(res =&gt; res.json())
  • 哦,当然,在那之前我没有关闭任何括号。刚刚编辑
  • 感谢您的帮助,但现在我的浏览器控制台显示我的 res 未定义。还有Cannot read property 'json' of undefined
  • 是在 404 之后吗? 200 可以正常运行吗?
  • 已编辑答案,附有解释和已解决的 SO 帖子的链接。
【解决方案2】:

你可以添加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 密钥,因为它是私人物品,任何人都可以使用此密钥,您不应在互联网上共享它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-23
    • 2011-12-26
    • 2013-07-05
    • 2015-10-25
    • 1970-01-01
    • 2014-08-09
    • 2013-05-01
    • 1970-01-01
    相关资源
    最近更新 更多