api - 我不断收到“错误 TypeError:无法在 updateUI (app.js:66) 处读取未定义的属性(读取 'temp')”
问题描述
我正在使用异步 javascript 制作一个简单的 Web 应用程序我正在使用打开的天气地图中的 api,除了更新 ui 外一切正常,我不断收到此错误 TypeError: Cannot read properties of undefined (reading 'temp') at updateUI (app .js:66)" 我认为问题在于将数据传递给项目数据对象,因为当我将其转换为数组时,一切正常,这是我的服务器端代码注释:我需要 express、cors 和 boyparser
let entry = [];
projectData["entry"] = entry;
//post request
app.post('/add', function(request, response) {
let data = request.body;
console.log(data);
let latestEntry = {
temp: data.temp,
date: data.date,
content: data.content
}
entry.push(latestEntry);
response.send(projectData);
});
这是我编写的客户端代码,更新 ui 功能无法正常工作,我没有超出温度但结果显示在控制台中
//
//Post 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) // body data type must match "Content-Type" header
});
try {
const newData = await response.json();
return newData;
} catch (error) {
console.log("error", error);
}
}
//update UI function
const updateUI = async () => {
const request = await fetch('/all');
try {
const allData = await request.json();
document.getElementById('temp').innerHTML = `Current temperature: ${allData[0].temp} degree celsius`;
document.getElementById('date').innerHTML = `Today's date: ${allData[0].date} `;
document.getElementById('content').innerHTML = `I feel: ${allData[0].content}`;
} catch (error) {
console.log("error", error);
}
}
解决方案
推荐阅读
- swiftui - 如何在 SwiftUI 中打开 about:blank
- python - 将表格格式的文本打印到 tk.Text 小部件中,未按预期对齐
- python - 如何根据 Python 中的散点图颜色制作等高线图?
- vue.js - Vue中的页面幻灯片转换?
- streamlit - 没有名为 streamlit.__main__ 的模块;'streamlit' 是一个包,不能直接执行
- php - 安装后mongo没有出现在phpinfo中
- time-complexity - 这个给定代码片段的空间复杂度是多少?
- javascript - 数组数据提取
- reactjs - 反应:将状态传递给 setInterval 时出现问题
- c# - Web 应用程序控制器将项目添加到队列并在其他地方使用