Search code examples
javascriptjsonapijson-server

why page reload when posting or updating and item using fake rest api with json server


I'm using Json-Server for mocking API requests, when fetching the post/ update the page reloads in each time which i do not know why, i searched for it and cant find any solution for that,

NB: i am following a javascript Tuturial and it didnt refresh from his side but it did in my side despite the codes were the same

class EasyHTTP {

  async post(url,data){
    const response = await fetch(url,{
                                      method: 'POST',
                                      headers:{'content-type':'application/json'},
                                      body: JSON.stringify(data)
                                    });
    const resData = await response.json();
    if(resData){
      return resData;
    }else{
      await Promise.reject(new Error('ERROR: Dont Know'));
    }
  }
}

const http = new EasyHTTP();

// Submit POST
document.querySelector('.post-submit').addEventListener('click',submitPost);

function submitPost(e){
  e.preventDefault(); 
   //e.stopPropagation(); 
  const title = document.querySelector('#title').value;
  const body = document.querySelector('#body').value;

  const data = {
    title,
    body
  };

    http.post('http://localhost:3000/posts',data)
    .then(res => {
      console.log(res);
    })
    .catch(err => console.log(err));
}
       <input
            type="text"
            id="title"
            class="form-control"
            placeholder="Post Title"
          />
  <textarea
            id="body"
            class="form-control"
            placeholder="Post Body"
          ></textarea>
<button  class="post-submit">Post It</button>

h post and i do not know where the problems comes from,


Solution

  • i found the solution, as I'm using VS code I disabled live-server extension and it worked perfectly fine now with no refreshing.