Почему на моей консоли отображается неопределенное значение? - PullRequest
1 голос
/ 01 августа 2020

Я пытаюсь выполнить вызов AJAX с помощью fetch и promises. Я хочу отобразить город в консоли. Мне удалось отобразить температуру, но по какой-то причине местоположение отображается как неопределенное. Пожалуйста, порекомендуйте. Ниже мой код:

function getWeather(woeid) {
  // You wanna pass in the API URL into the fetch method as a string
  // Moesif Orign & CORS chrome extension is used to fetch this API since we are practicing locally
  fetch(`https://www.metaweather.com/api/location/${woeid}/`) // Automatically returns a promise
    .then(result => { // The fetch AJAX request will be called result
      console.log(result);
      return result.json(); // This will process the data (body:ReadableSteam). Returns a promise 
    })
    .then(data => {
      //console.log(data);
      const today = data.consolidated_weather[0];
      console.log(`Todays temperatures in ${today.title} will stay between ${today.min_temp} and ${today.max_temp}.`);
    })
    .catch(error => console.log(error));
}

getWeather(2487956);
getWeather(44418);

1 Ответ

2 голосов
/ 01 августа 2020

Как Ник говорит , похоже, вам нужен правильный параметр данных. Таким образом, этот код на самом деле исправляет это:

const todaySrc = data.sources[0];
todaySrc.title // BBC

Вот полный фрагмент:

function getWeather(woeid) {
  // You wanna pass in the API URL into the fetch method as a string
  // Moesif Orign & CORS chrome extension is used to fetch this API since we are practicing locally
  fetch(`https://www.metaweather.com/api/location/${woeid}/`) // Automatically returns a promise
    .then(result => { // The fetch AJAX request will be called result
      console.log(result);
      return result.json(); // This will process the data (body:ReadableSteam). Returns a promise 
    })
    .then(data => {
      //console.log(data);
      const today = data.consolidated_weather[0];
      const todaySrc = data.sources[0];
      console.log(`Todays temperatures in ${todaySrc.title} will stay between ${today.min_temp} and ${today.max_temp}.`);
    })
    .catch(error => console.log(error));
}

getWeather(2487956);
getWeather(44418);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...