首页 > 解决方案 > 我不断收到“错误 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);
  }
}

标签: apiasynchronouserror-handling

解决方案


推荐阅读