Я должен нажать кнопку поиска два раза, чтобы получить данные из API - PullRequest
0 голосов
/ 20 апреля 2019

Когда я нажимаю кнопку поиска в первый раз, появляются две ошибки:

  1. main.js: 68 GET https://cors -anywhere.herokuapp.com / https://api.darksky.net/forecast/API_key/ 404 (не найдено)

  2. Uncaught (в обещании) SyntaxError: Неожиданный токен N в JSON в позиции 0.

Но когда я нажимаю кнопку поиска во второй раз, ошибка исчезает.поэтому мне нужно дважды нажать кнопку поиска, чтобы получить данные из API.

index.html

<form class="searchForm" method="POST">
    <div class="form-div">
        <label for="loaction">Enter a location</label>
        <input type="text" class="searchForm-input" id="loaction" placeholder="Location">
        <button type="submit">Search</button>
    </div>
</form>
<div class="echo">--</div>
<div class="location">
    <h1 class="location-timezone">Timezone</h1>
</div>
<div class="temperature">
    <div class="degree-section">
        <h2 class="temperature-degree">34</h2>

        <span>F</span>

    </div>
</div>

main.js

let lat1 = '';
let form = document.querySelector('.searchForm');
form.addEventListener('submit', handleSubmit);

function handleSubmit(event) {
    event.preventDefault();
    const input = document.querySelector('.searchForm-input').value;
    // remove whitespace from the input
    const searchQuery = input.split(' ').join('+');
    // print `searchQuery` to the console
    console.log(searchQuery);

    let geocodeURL = `https://maps.googleapis.com/maps/api/geocode/json? 
        address=${searchQuery}&key=api_key`;

    fetch(geocodeURL)
        .then(response => {
            return response.json();
        })
        .then(data => {

            let max = data.results[0].geometry.location;
            console.log(max);

            let max1 = max.lat + ',' + max.lng;
            console.log(max1);
            lat1 = max1;
            console.log(lat1);
        })
    console.log(geocodeURL);


    let temperatureDegree = document.querySelector('.temperature-degree');
    let locationTimezone = document.querySelector('.location-timezone');
    let echos = document.querySelector('.echo');
    echos.textContent = searchQuery;

    const proxy = 'https://cors-anywhere.herokuapp.com/';
    const api =
        `${proxy}https://api.darksky.net/forecast/aki_key/${lat1}`;

    fetch(api)
        .then(response => {
            return response.json();
        })
        .then(data => {
            console.log(data);
            const {temperature} = data.currently;
            temperatureDegree.textContent = temperature;

            locationTimezone.textContent = data.timezone;

        })
}

1 Ответ

1 голос
/ 20 апреля 2019

У вас есть две асинхронные операции, для которых вторая должна использовать результаты первой операции AJAX для продолжения:

fetch(geocodeURL)
        .then(response => {
            return response.json();
        })
        .then(data => {

          let max = data.results[0].geometry.location;
          console.log(max);

          let max1 = max.lat+',' + max.lng;
          console.log(max1);
           lat1 = max1; <-- lat1 is used in second AJAX call
          console.log(lat1);
        })
    console.log(geocodeURL);

И несколько строк спустя:

        const proxy = 'https://cors-anywhere.herokuapp.com/';
        const api = 
        `${proxy}https://api.darksky.net/forecast/aki_key/${lat1}`; // <-- lat1 will be undefined

Итак, когда вынажмите кнопку поиска, первая сработает, а когда вернется, заполнит переменную lat1.Так как это результат Обещания, оно сработает, как только оно будет выполнено, в то время как основной поток продолжит работу и выполнит следующий оператор fetch(api), не дожидаясь установки lat1.Просто переместите второй вызов AJAX в разрешение Promise:

event.preventDefault();
const input = document.querySelector('.searchForm-input').value;
// remove whitespace from the input
const searchQuery = input.split(' ').join('+');
// print `searchQuery` to the console
console.log(searchQuery);

let geocodeURL = `https://maps.googleapis.com/maps/api/geocode/json? 
address=${searchQuery}&key=api_key`;

fetch(geocodeURL)
            .then(response => {
                return response.json();
            })
            .then(data => {

                let max = data.results[0].geometry.location;
                console.log(max);

                let max1 = max.lat+',' + max.lng;
                console.log(max1);
                lat1 = max1;
                console.log(lat1);

                let temperatureDegree = document.querySelector('.temperature- 
                 degree');
                let locationTimezone = document.querySelector('.location-timezone');
                let echos = document.querySelector('.echo');
                echos.textContent = searchQuery;

                const proxy = 'https://cors-anywhere.herokuapp.com/';
                const api = 
                `${proxy}https://api.darksky.net/forecast/aki_key/${lat1}`;

                fetch(api)
                    .then(response => {
                        return response.json();
                    })
                    .then(data => {
                        console.log(data);
                        const {temperature} = data.currently;
                        temperatureDegree.textContent = temperature;

                        locationTimezone.textContent = data.timezone;

                    })
                }
            })
console.log(geocodeURL);
...