【发布时间】:2021-06-11 10:46:35
【问题描述】:
我正在浏览 Coding Train 视频,并通过从 Poemist API 获取数据来尝试我自己的看法。我可以从 API 中获取诗歌的标题以显示在控制台中;但是,我无法让它显示在 HTML 上(它只是显示未定义)。有人知道我在这里可能做错了什么吗?下面是我的代码。
<!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);
}
</script>
</body>
</html>
【问题讨论】:
-
你在 catchPoem 中什么都不返回,所以你在 then 中没有定义
标签: javascript async-await fetch