【发布时间】: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我不关心。不过谢谢!
-
任何人使用该密钥所做的任何事情都可能与生成该密钥的人相关联。我知道你说它只是一个测试项目,但如果有人对它进行恶意操作,它仍然是他们用来执行此操作的密钥。