簡體   English   中英

未捕獲的類型錯誤:response.json 不是 HTMLButtonElement 的函數

[英]Uncaught TypeError: response.json is not a function at HTMLButtonElement

我堅持這個我是網絡開發的新手,任何幫助將不勝感激。 無法弄清楚我的代碼有什么問題,我收到一個錯誤 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>

使用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>

如前所述, 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 的代碼之前運行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM