Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Response.json is not a function

I need your help. I’m trying to learn how to execute a POST query to create a new object in a database using fetch. I use pure javascript. However, I get an error that looks like this:

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

What am I doing wrong? Thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
 }
}

>Solution :

You need to prefix them with await. Check here to understand 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)
 }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading