TransWikia.com

Ошибка при запросе данных о погоде

Stack Overflow на русском Asked by Bohdan on January 28, 2021

async function sendRequesr(city) {
    const apiKey = "825b534bf099d1d076f6921161eae5d3"
    const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?id=${city}&appid=${apiKey}`);
    const result = await response.json();
    return result;
}

async function sendCity() {
    const url = "https://raw.githubusercontent.com/alexanderkuzmenko/weatherapplication/master/cities.json"
    const response = await fetch(url);
    const result = await response.json();
    return result;
}

sendCity().then((response) => {

    let arr = [];
    let mass = [];
    let cities = document.getElementById('cities')
    for (let i = 0; i < response.length; i++) {
        arr[i] = response[i].city
        let a = document.createElement('a')
        a.innerHTML = `${arr[i]}`
        a.classList = "list-group-item list-group-item-action"
        a.href = "#"
        mass.push(a)
        cities.appendChild(a)
    }
    for (let i = 0; i < arr.length; i++) {
        let elementById = document.getElementById('idcities')
        mass[i].addEventListener('click', function (){
            for(let i = 0; i < arr.length; i++){
                mass[i].classList.remove('active')
            }
            mass[i].classList.add("active")
            sendRequesr(mass[i]).then((response) =>{
                elementById.innerHTML = `Weather in ${arr[i]}`
                pres.innerHTML = `${response.main.pressure}`
                hum.innerHTML = `${response.main.humidity}`
                temp.innerHTML = `${Math.round(response.main.temp - 273, 0)}`
                icon.src = `http://openweathermap.org/img/w/${response.weather[0].icon}.png`
            }).catch((error) => {
                elementById.innerHTML = "error"
                pres.innerHTML = "error"
                hum.innerHTML = "error"
                temp.innerHTML = "error"
                icon.src = "error"
                console.log(error)
            });
        })
    }
}).catch((error) => {
    console.log(error)

});
<!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
          integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

    <title>Hello, world!</title>
</head>
<body>
<header>
    <div class="container">
        <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
            <a class="navbar-brand" href="#">Navbar</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
                    aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav mr-auto">
                    <li class="nav-item active">
                        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">Link</a>
                    </li>
                </ul>
                <form class="form-inline my-2 my-lg-0">
                    <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
                    <button class="btn btn-outline-warning my-2 my-sm-0" type="submit">Search</button>
                </form>
            </div>
        </nav>
    </div>

</header>

<section id="main" class="mt-3">
    <div class="container">
        <div class="row">
            <div class="col-6 col-md-4 col-lg-3">
                <div class="list-group" id="cities" >
                </div>
            </div>
            <div class="col-6 col-md-8 col-lg-9">
                <div class="card">
                    <div class="card-body">
                        <h3 class="card-title" id="idcities"></h3>
                        <img src="http://openweathermap.org/img/wn/[email protected]" alt="" id="icon">
                        <table class="table table-striped" >
                            <tr>
                                <th>Pressure</th>
                                <td id="pres"></td>
                            </tr>
                            <tr>
                                <th>Humidity</th>
                                <td id="hum"></td>
                            </tr>
                            <tr>
                                <th>Temperature</th>
                                <td id="temp"></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
        integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
        crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
        crossorigin="anonymous"></script>
<script src="task.js"></script>

</body>
</html>

Я беру список городов по url

Данные по городам получаю с OpenWeatherMap

Почему у меня не работает, где я допустил ошибку

на картинке пример как должно получится

введите сюда описание изображения

у меня же введите сюда описание изображения

2 Answers

Функция sendRequest(city) ожидает параметр строку (ID города) А вы передаёте в неё DOM элемент. Поправил чтоб передавался город, осталось только получить верный cityID.

async function sendRequesr(city) {
    const apiKey = "825b534bf099d1d076f6921161eae5d3"
    const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?id=${city}&appid=${apiKey}`);
    const result = await response.json();
    return result;
}

async function sendCity() {
    const url = "https://raw.githubusercontent.com/alexanderkuzmenko/weatherapplication/master/cities.json"
    const response = await fetch(url);
    const result = await response.json();
    return result;
}

sendCity().then((response) => {

    let arr = [];
    let mass = [];
    let cities = document.getElementById('cities')
    for (let i = 0; i < response.length; i++) {
        arr[i] = response[i].city
        let a = document.createElement('a')
        a.innerHTML = `${arr[i]}`
        a.classList = "list-group-item list-group-item-action"
        a.href = "#"
        a.dataset.city = arr[i]; //Проставить верный cityID
        mass.push(a)
        cities.appendChild(a)
    }
    for (let i = 0; i < arr.length; i++) {
        let elementById = document.getElementById('idcities')
        mass[i].addEventListener('click', function (){
            for(let i = 0; i < arr.length; i++){
                mass[i].classList.remove('active')
            }
            mass[i].classList.add("active")
            sendRequesr(mass[i].dataset.city).then((response) =>{
                elementById.innerHTML = `Weather in ${arr[i]}`
                pres.innerHTML = `${response.main.pressure}`
                hum.innerHTML = `${response.main.humidity}`
                temp.innerHTML = `${Math.round(response.main.temp - 273, 0)}`
                icon.src = `http://openweathermap.org/img/w/${response.weather[0].icon}.png`
            }).catch((error) => {
                elementById.innerHTML = "error"
                pres.innerHTML = "error"
                hum.innerHTML = "error"
                temp.innerHTML = "error"
                icon.src = "error"
                console.log(error)
            });
        })
    }
}).catch((error) => {
    console.log(error)

});
<!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
          integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

    <title>Hello, world!</title>
</head>
<body>
<header>
    <div class="container">
        <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
            <a class="navbar-brand" href="#">Navbar</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
                    aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav mr-auto">
                    <li class="nav-item active">
                        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">Link</a>
                    </li>
                </ul>
                <form class="form-inline my-2 my-lg-0">
                    <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
                    <button class="btn btn-outline-warning my-2 my-sm-0" type="submit">Search</button>
                </form>
            </div>
        </nav>
    </div>

</header>

<section id="main" class="mt-3">
    <div class="container">
        <div class="row">
            <div class="col-6 col-md-4 col-lg-3">
                <div class="list-group" id="cities" >
                </div>
            </div>
            <div class="col-6 col-md-8 col-lg-9">
                <div class="card">
                    <div class="card-body">
                        <h3 class="card-title" id="idcities"></h3>
                        <img src="http://openweathermap.org/img/wn/[email protected]" alt="" id="icon">
                        <table class="table table-striped" >
                            <tr>
                                <th>Pressure</th>
                                <td id="pres"></td>
                            </tr>
                            <tr>
                                <th>Humidity</th>
                                <td id="hum"></td>
                            </tr>
                            <tr>
                                <th>Temperature</th>
                                <td id="temp"></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
        integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
        crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
        crossorigin="anonymous"></script>
<script src="task.js"></script>

</body>
</html>

Answered by mego4iter on January 28, 2021

z [1]: https://i.stack.imgur.com/t3Z3x.png

Не верный API key. Возможно закончился или отклонили

Answered by mego4iter on January 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP