【问题标题】:Uncaught TypeError: response.json is not a function at HTMLButtonElement未捕获的 TypeError:response.json 不是 HTMLButtonElement 处的函数
【发布时间】:2021-01-25 05:20:01
【问题描述】:

我坚持这一点,我是网络开发的新手,任何帮助将不胜感激。无法弄清楚我的代码有什么问题,我收到一个错误 Uncaught TypeError: response.json is not a function

const getButton = document.querySelector('.get')
function getData(){
  const response = fetch("https://reqres.in/api/users");
  const data = response.json();
  console.log(data)
}
 getButton.addEventListener('click',getData)
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <button class="get">GET</button>
    </div>
    <script src="sandbox.js"></script>
</body>
</html>

【问题讨论】:

标签: javascript json ecmascript-6 async-await fetch


【解决方案1】:

如前所述,fetch() 是异步的。试试这个:

const getButton = document.querySelector('.get')
function getData(){
    const response = fetch("https://reqres.in/api/users")
        .then(function(data) {
            // This will run on on response from the server
            // AAA
            console.log(data);
        })
        .catch(function(error) {
            // Deal with errors here
        });
    // BBB
}
getButton.addEventListener('click',getData);

所以 BBB 的代码可能会在 AAA 的代码之前运行

【讨论】:

    【解决方案2】:

    使用async/await

    const getButton = document.querySelector('.get')
    
    async function getData() {
      const response = await fetch("https://reqres.in/api/users");
      const data = await response.json();
      console.log(data)
    }
    
    getButton.addEventListener('click', getData)
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    
    <body>
      <div>
        <button class="get">GET</button>
      </div>
      <script src="sandbox.js"></script>
    </body>
    
    </html>

    【讨论】:

    • 由于 OP 是初学者...请解释为什么 OPs 脚本不起作用,为什么 await 有帮助以及为什么 OP 还需要 async。所以 OP 理解了潜在的问题,并使这个答案对未来的读者更有价值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    • 2020-02-24
    • 1970-01-01
    相关资源
    最近更新 更多