首页 > 解决方案 > 使用 GET 方法更新 UI

问题描述

我正在开发一个项目,以使用 node js & express 从 openweathermap 获取 api,然后更新 UI。我正在尝试使用 GET 数据更新页面的 UI,但它不起作用。它打印 undefined 而不是所需的值。

它可以工作并从终端和控制台上的 openweathermap 获取 api。

任何帮助,将不胜感激!

/* Global Variables */
const date = document.getElementById('date').value;
const temp = document.getElementById('temp').value;

// Create a new date instance dynamically with JS
let d = new Date();
let newDate = d.getMonth()+'.'+ d.getDate()+'.'+ d.getFullYear();

//baseURL & apiKey
const baseURL = `http://api.openweathermap.org/data/2.5/weather?zip=`;
const apiKey = `&appid=...`;

//event listener when user clicks generate button
const button = document.getElementById('generate');
button.addEventListener('click', performAction);

//event listener function
function performAction(event) {
  const zip = document.getElementById('zip').value;
  const feelings = document.getElementById('feelings').value;

  getData(baseURL, zip, apiKey)
    .then(function (data) {
      console.log(data);
      postData('/add', {date: newDate, temp: data.main.temp, feelings: feelings});
      updateUI();
})
};

//function to fetch api data
const getData = async (baseURL, zip, apiKey) => {
  const res = await fetch(baseURL+zip+apiKey)

  try {
    const data = await res.json();
    return data;
    console.log(data);
  }catch(error) {
    console.log("error", error);
  }
}

// user input post data function
const postData = async (url = '', data = {}) => {
  const response = await fetch(url, {
    method: 'POST',
    credentials: 'same-origin',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data)
  });

  try {
    const newData = await response.json();
  }catch (error) {
    console.log("error", error);
  }
};

//updating UI
const updateUI = async () => {
  const request = await fetch('/all');
  try{
    const allData = await request.json();

    document.getElementById('date').innerHTML = allData.date;
    document.getElementById('temp').innerHTML = allData.temp;
    document.getElementById('content').innerHTML = allData.content;

  }catch(error){
    console.log("error", error);
  }
}

标签: javascriptnode.jsapi

解决方案


推荐阅读