javascriptjsonjson-server

Why is the page refreshed after javascript post request?


When I send post request JSON to server username and score page being refreshed. Patch request does not have this problem page not being refreshed.

I need the page should not be refreshed because my score modal closes and the game restarts.


let vaxt = 5;
let timeStart = false;


input.addEventListener('keydown', ()=>{


  if (!timeStart) {

    timeStart = true;

    let timer = setInterval(()=>{
      vaxt--;
      time.innerText = `${vaxt}`;
   
      if (vaxt === 0) {
         clearInterval(timer);
         input.disabled = true;
         scoreModal.style.display = 'block';

         fetch('http://192.168.0.105:5500/users')
          .then(res => res.json())
          .then(users => {
             const existingUser = users.find(user => user.username === username)

             if (existingUser) {
                if (score > existingUser.score) {
                   fetch(`http://192.168.0.105:5500/users/${existingUser.id}`, {
                      method: 'PATCH',
                      headers: {
                       'Content-Type': 'application/json'
                      },
                      body: JSON.stringify({
                         score: score
                      })
                   })
                }
             }else{
                 fetch('http://192.168.0.105:5500/users', {
                     method: 'POST',
                     headers:{
                       'Content-Type': 'application/json'
                     },
                     body: JSON.stringify({
                        username: username,
                         score: score
                     })
                 })
             }
          })

      }
   
   }, 1000);
  }

});

Solution

  • Problem solved.I created my db.json server in seperate folder different from my project file

    enter image description here

    enter image description here

    enter image description here