如何从网站获取 api 数据,它显示 TypeError 消息

function getInfo() {

  fetch("https://swapi.co/api/people")

    .then(response => response.json())

    .then(function(data) {

      console.log(data);


    })

    .catch(function(error) {

      // If there is any error you will catch them here

      console.log(error);

    });

}


const newPerson = document.getElementById('newQuote')

newPerson.addEventListener('click', getInfo); // new quote on button click

window.onload = getInfo; // new quote on page load

我编写了这段代码并在控制台中收到以下消息:TypeError{}


蛊毒传说
浏览 138回答 1
1回答

慕尼黑8549860

您不应将该async函数用作事件侦听器的函数。您应该做的是async在侦听器函数中调用该函数。function getInfo() {&nbsp; fetch("https://swapi.co/api/people")&nbsp; &nbsp; .then(response => response.json())&nbsp; &nbsp; .then(function(data) {&nbsp; &nbsp; &nbsp; console.log(data);&nbsp; &nbsp; })&nbsp; &nbsp; .catch(function(error) {&nbsp; &nbsp; &nbsp; // If there is any error you will catch them here&nbsp; &nbsp; &nbsp; console.log(error);&nbsp; &nbsp; });}const newPerson = document.getElementById('newQuote');newPerson.addEventListener('click', function(e) {&nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp; getInfo();});window.addEventListener('load', function(e) {&nbsp; &nbsp; getInfo();});<button id="newQuote">New Quote</button>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript