簡體   English   中英

Response.json 不是 function

[英]Response.json is not a function

我需要你的幫助。 我正在嘗試學習如何執行 POST 查詢以使用 fetch 在數據庫中創建新的 object。 我使用純 javascript。 但是,我收到一個如下所示的錯誤:

Mistake TypeError: response.json is not a function at sendData (scrip4t.js:22) at HTMLButtonElement.onclick

我究竟做錯了什么? 謝謝

HTML

<input type="text" id="name">
<input type="text" id="price">
<input type="text" id="description">
<button id="send" onclick="sendData()">submit</button>

JS

const url = `http://localhost:8081/laptop`
let name = document.getElementById('name')
let price = document.getElementById('price')
let description = document.getElementById('description')

function sendData () {

let name_of_laptop = name.value
let price_of_laptop = price.value
let laptop_description = description.value

let data = {name: name_of_laptop, price: price_of_laptop, description: laptop_description}

try {
    const response = fetch(url, {
        method: 'POST',
        body: JSON.stringify(data),
        headers: {
            'Content-Type' : 'application/json'
        }
    });
    let json = response.json();
    console.log('Success', JSON.stringify(json))
} catch (error) {
    console.error('Mistake',error)
 }
}

您需要在它們前面加上await 在這里查看以了解async/await

...

async function sendData () {

...

try {
    const response = await fetch(url, {
        method: 'POST',
        body: JSON.stringify(data),
        headers: {
            'Content-Type' : 'application/json'
        }
    });

    let json = await response.json();
    console.log('Success', JSON.stringify(json))
} catch (error) {
    console.error('Mistake',error)
 }
}

您需要使用 promise 鏈或 async/await 如下代碼:

fetch(url, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
        'Content-Type' : 'application/json'
    })
.then(response => response.json())
.then(data=> console.log(data));

或者

async function sendData () 
 const response = await fetch(url, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
        'Content-Type' : 'application/json'
    }
 });

 let data = await response.json();
 console.log(data);
}

暫無
暫無

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

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