简体   繁体   中英

JavaScript API returns to undefined after calling another API

//app.js
const SEARCH_VIEW  = document.getElementById('search_view');
const RESULTS_VIEW = document.getElementById('results_view');
const FORECAST_VIEW = document.getElementById('forecast_view')


function loadCities(){


    const cities = ["London", "Paris", "Madrid", "Lisbon","Ohrid"];

    var options = null;

    var dest = document.getElementById('dest');

    //Looping the cities
    cities.forEach(city => {
        options += '<option>' + city +'</options>';
    });

    dest.innerHTML = options;
}

function gettingWeather(){

    // 1. Open the Url
    var dest = document.getElementById('dest').value;
    var url = ('http://api.openweathermap.org/data/2.5/weather?q='+ dest + '&appid=exampleAppId');
    console.log(url);
    console.log(dest);

    // 2. Fetch the URL

    fetch(url)
        .then(response => {
        if(response.status !== 200){
            console.error("API failed, Status Code " + response.status);
            return;
        }
        console.log(response);
    // 3.We make the response .json and open the data

        response.json().then(data => {
        console.log(data);
        RESULTS_VIEW.style.visibility = 'visible';
        // Temperature
        document.getElementById('Temperature').textContent = data.main.temp;    

        //Wind

        document.querySelector('.Wind').textContent = data.wind.speed * data.wind.deg;
        //Description
        document.querySelector('.Description').textContent = data.weather[0].description;   
        });

        }).catch(err => {
        console.error("Fetch error "+ err);
    });
}

function forecast(){
    const API_BASE = 'http://api.openweathermap.org/data/2.5/forecast?mode=json&';
    const API_KEY = 'appid=exampleAppId&';
    var dest = document.getElementById('dest').value;
    var url = API_BASE + API_KEY + 'q=' + dest.value;
    console.log(url);
    console.log(dest.value);

    // 2. Fetch the URL

    fetch(url)
        .then(response => {
        if(response.status !== 200){
            console.error("API failed, Status Code " + response.status);
            return;
        }
            console.log(response);
    // 3.We make the response .json and open the data

        response.json().then(data => {
            console.log(data);

            RESULTS_VIEW.style.visibility = 'hidden';
            FORECAST_VIEW.style.visibility= 'visible';



    });

    }).catch(err => {
             console.error("Fetch error "+ err);
    });
}

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Weather App</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width ,initial-scale=1">
<link href="styles.css" type="text/css" rel="stylesheet">

</head>
<body onload="loadCities();">







<div class="container">

    <div id = "results_view">
         <div class="inputWrapper">
            <h1> Weather App </h1>
            <p>Choose a city.</p>
            <select  id="dest" onchange="gettingWeather();"  width=150 style="width:150px" ></select><br>
            <label>Temperature</label>
            <label class="Temperature" id="Temperature"></label><br>
            <label>Wind</label>
            <label class="Wind" id="Wind"></label><br>
            <label>Description</label>
            <h1 class="Description" id="Description"></h1>

            <button onclick="forecast();">Forecast</button>
        </div><!-- InputWrapper -->
    </div>
    <div id="forecast_view">
        <h1>ForeCast</h1>
    </div>

 </div> <!-- end container -->




 <script src="app.js"></script> 
</body>
</html>

My task is to choose random 5 European cities and show some attributes but when a button is clicked I need to show a forecast of that city. I attempt to use Lexical Scoping to and half of my application works the easy part where i show some attribute taken from the API, when i clicked the button forecast I have error with the response Error but the error is also the city i choose.If I use any city the, in the forecast is undefined. I am not sure why I have this error and i dont have any insides tried closure If you don't know any answer I would appreciate even an insight or reference of work similar done.

Thank you

The problem is that your variable "dest" already contains the value. So you have in "dest" the name of your city and you use dest.value which is undefined because dest is a string and has no property called value. to fix your code just remove .value in the url:

const API_BASE = 'http://api.openweathermap.org/data/2.5/forecast?mode=json&';
const API_KEY = 'appid=6c345b20d0c8fac21a36761eb7d6cd38&';
var dest = document.getElementById('dest').value;
var url = API_BASE + API_KEY + 'q=' + dest; // only dest NOT dest.value
console.log(dest); // the city selected

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM