0

I am facing the issue that when I am posting a data using fetch API, I am getting the data posted twice. my service-worker code code is like this:

self.addEventListener('fetch', function(event) {
  if(event.request.method === "POST" || event.request.method === "PUT" || event.request.method ==="CREATE" ){
   return fetch(event.request);
  };
  if(event.request.method === "GET"){
  event.respondWith(    
    caches.open(cacheName)
       .then(function(cache) {
      return cache.match(event.request).then(function (response) {
        return response || fetch(event.request).then(function(response) {
         // cache.put(event.request, response.clone());
          return response;
        });
      });
    })
  );
  }
}) 

and JS file code is like this:

let leaveRequestForm = document.getElementById('leave-request');
    leaveRequestForm.addEventListener('submit',function (e){
    e.preventDefault();

let formData = new FormData(leaveRequestForm);

fetch("https://myserver/api/leave-request/create-leave-request", { 

    method: 'post', 
    "headers": {        
        'id':id,            
    },        
    body: formData
}).then(function (res) { 

    if (res.status >= 200 && res.status < 400) {             
        var successMsg = "<div class='alert-success'>Your Request is Submitted Successfully.  <br>Thanks</div>";
        var target = _d.qs(".content-target");
        target.innerHTML = successMsg;

   return res.json(); 
    } else { 
  console.log('Status Code: ' + response.status);      
     return; 
    } 
}).then(function (resp) { 
    //process the response 
})
});

What I am missing here? I can comment-out the code in service-worker return fetch(event.request);, but I want to send the request through service worker as I plan to offlice submit as well

Joshi
  • 2,730
  • 5
  • 36
  • 62
  • Side note (maybe related?): An accurate check for a successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has a value of true. - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch – A. Meshu May 13 '20 at 21:28
  • What do you mean two fetch requests are happening? – abraham May 14 '20 at 11:29
  • @abraham - The data is saved twice in the database, if I am submitting the form once. and when I see the network activity, I can see two requests being created one directly from JS file and from sw.js – Joshi May 14 '20 at 12:59
  • If you're basing this on what you see in Chrome's DevTools, it sounds like https://stackoverflow.com/a/33655173/385997 – Jeff Posnick May 15 '20 at 14:40

0 Answers0