ERR_NAME_NOT_RESOLVED in OpenWeather Api Call



我正在整理我的第一个Api项目,我正在使用OpenWeather请求城市的条件。当我运行代码时,我得到了ERR_NAME_NOT_RESOLVED."我已经检查和重新检查了我的URL格式,我没有得到任何错误时运行我的代码。谁能给我指个正确的方向?

HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script defer src="./js/script.js"></script>
<title>Weatherd</title>
</head>
<body>
<h1>Weatherd</h1>
<form>
<input type="text" placeholder="Search by city"/>
<input type="submit" value="Search"/>
</form>
<main>
<p>Weather for</p>
<p id="weatherFor"></p>

<p>Temperature: </p>
<p id ="temp"></p>

<p>Currently feels like: </p>
<p id="feelsLike"></p>

<p>Conditions: </p>
<p id="desc"></p>
</main>  
</body>
</html>

我JS

const $weatherFor = $('#weatherFor');
const $temp = $('#temp');
const $feelsLike = $('#feelsLike');
const $desc = $('#desc');
const $input = $('input[type="text"]');
let weatherData, userInput;
$('form').on('submit', handleGetData);
function handleGetData(event) {
event.preventDefault();
userInput = $input.val();
$.ajax({
url: 'https://www.api.openweathermap.org/data/2.5/weather?q='+userInput+'&APPID=15ff99dd07f18bda25869ab24d06891e'
}).then(
(data) => {
weatherData = data;
render();
},
(error) => {
console.log('bad request', error);
}
);
}
function render() {
$weatherFor.text(weatherData.weatherFor);
$temp.text(weatherData.temp);
$feelsLike.text(weatherData.feelsLike);
$desc.text(weatherData.desc);
}

这个问题已经问了一段时间了,但是考虑到这个问题到目前为止的访问量,这个答案可能会对某些人有所帮助。

const url = "api_url_here";
const result = await axios
.get(url)
.then((res) => {
const { status } = res;
return status && status == 200
? { ...res.data, status: 200 } // return data + status 200
: { status: 400 }; // create and return status 400 on error
})
.catch((err) => {
return { status: 400 }; // create and return status 400 on error
});
// work with the returned status
if(result.status == 200) {
// success
} else {
// error
}

我使用axios,但这个想法非常适合Fetch Api或Ajax。

最新更新