如何让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
相关产品推荐
相关产品推荐

