I'm practicing using the fetch API for a project I'm working on and having trouble getting a button to call a function that uses the fetch API to access an external API. Keep getting a 'Type Error: Failed to Fetch' message.
const uri = 'https://jsonplaceholder.typicode.com/posts';
    const initDetails = {
        method: 'get',
        headers: {
            "Content-Type": "application/json; charset=utf-8"
        },
        mode: "cors"
    }
    
    function getData() {
        fetch(uri, initDetails)
        .then(response => {
            if (response.status !== 200) {
                console.log('Looks like there was a problem. Status Code: ' +
                response.status);
                return;
            }
    
            console.log(response.headers.get("Content-Type"));
            return response.json();
            }
        )
        .then(myJson => {
            console.log(JSON.stringify(myJson));
        })
        .catch(err => {
            console.log('Fetch Error :-S', err);
        });
    }
    
    window.onload=function() {
        let myButton = document.getElementById("getData");
        myButton.addEventListener('click', getData);
    }
<form>
    <button id='getData'>Get Data</button>
   </form>
Your button is inside a form. The default action of buttons inside forms is to submit the form, which reloads the page and aborts the fetch request.
Either preventDefault() in the form submit handler, add type="button" to the <button> element, or (ideally, in this case) remove the <form> entirely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With