javascript - 使用 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);
}
}
解决方案
推荐阅读
- angular - Ag-Grid 分组单元格点击不提供 CellRendererParams
- c++ - 使用 boost 几何找到线段的交点
- html - 我无法在我的投资组合网站中将导航栏设置为置顶。我能做些什么来纠正它?
- python - pymc-learn:JupterLab 1.2.6 中的 RuntimeError
- javascript - sound.stop() 不起作用,但 sound.play() 在 Howlerjs 中工作?
- angular - 等到 subscribe 以 Angular 调用
- keycloak - Keycloak SAML 集成中的无效目标错误
- c# - 将推送通知发送到指定标签,Azure 通知中心不起作用
- pine-script - Pinescript 中基于部分时间的交易退出
- ubuntu - 我无法在 WSL2 开启的 Windows 10 上使用 npm 命令(ubuntu 终端)