首页 > 解决方案 > 获取请求在 html 中呈现未定义

问题描述

我的 html 块中有这个 Vanilla JS 代码


<label for="weather"></label><input value="copenhagen" type="text" id="weather" placeholder="Enter your name to get weather">
<button onClick="getValue()">Submit</button>

<div id="weather-box"></div>
<script>
    function getValue() {
        const form = document.getElementById('weather').value;
        const weatherBox = document.getElementById('weather-box')
        console.log(form);
        fetch(`http://localhost:3000/weather?city=${form}`)
                .then(res => res.json())
                .then(data => {
                    console.log(data)
                    weatherBox.innerHTML = `
                    weather is ${data.summary}
                    temperature is ${data.temperature}
                    `
                })
    }


</script>

问题是,即使数据被正确注销,它在呈现的 html 代码中给出了 undefined 。

为什么会发生这种情况,以及如何解决它?

编辑:

我已经添加了输出console.log(data)

在此处输入图像描述

标签: javascripthtml

解决方案


Yourconsole.log(data)表示您的响应 ( data) 有一个称为的属性data,它包含您想要的信息。

您可以通过data.data.summary(或者更好的是,将您的回复重命名为response)来访问它。

另一种方法是对其进行解构

.then(({data}) => {
  weatherBox.innerHTML = `
  weather is ${data.summary}
  temperature is ${data.temperature}
  `
})

推荐阅读