TypeError while Fecthing data from API

I am trying to send a “POST” request through fetch() to an API while a form is submitted. And then logging the sent data to the console. But it showing TypeError: NetworkError when attempting to fetch resource.
The HTML code:

<button id="get-posts">Get Posts</button>
    <form id="addPost">
        <input type="text" name="postTitle" id="postTitle">
        <textarea name="postBody" id="postBody" cols="30" rows="10"></textarea>
        <input type="submit" value="submit">
    </form>
 <div id="output"></div>

The JavaScript code:

  document.querySelector('#addPost').addEventListener('submit', addPost);
    function addPost(){
        let title=document.querySelector('#postTitle').value;
        let body=document.querySelector('#postBody').value;
        fetch('https://jsonplaceholder.typicode.com/posts',{
            method:'POST',
            headers:{
                'Accept':'application/json, text/plain,*/*',
                'Content-type':'application/json'
            },
            body:JSON.stringify({
                title:title,
                body:body
            })
        })
        .then((res)=> res.json())
        .then((data)=>console.log(data))
    }

I can’t figure out where is the problem. Help me guys!
Thanks in advance!

hey @riyadif7,

As your not using the form to actually post the data you might need to add a preventDefault to your function

function addPost(e) {
     e.preventDefault()
    //rest of your code
}

this might be your problem

oh! yes! I was the problem. Thanks @biscuitmanz.

1 Like