You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Fetch请求获取到的数据正常显示在HTML页面上

问题根因

你定义的catchPoem是异步函数,所有async函数如果没有显式使用return返回值,它最终返回的Promise对象的resolve结果默认为undefined。你已经在函数内部正确拿到了诗歌标题并打印到控制台,但没有把这个值返回给外部调用的.then()方法,所以赋值到页面的poem值就是undefined。

修复方案

只需要在catchPoem函数末尾添加返回标题的语句即可,修改后的代码如下:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Fetch a poem</title>
  </head>
  <body>
    <h1>Fetch a Poem</h1>
    <p id="poem">title</p>
    <script>
      console.log('about to fetch a poem');
      catchPoem()
        .then(poem => {
          document.getElementById('poem').innerText = poem;
          console.log('yay');
        })
        .catch(error => {
          console.log('error!');
          console.error(error);
        });

      async function catchPoem() {
        const response = await fetch('https://www.poemist.com/api/v1/randompoems');
        let json = await response.json();
        let title = json[0].title
        console.log(title);
        return title; // 新增返回标题的代码
      }
    </script>
  </body>
</html>

内容的提问来源于stack exchange,提问作者Ivy Chen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 14:24:10