Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch Keep Alive is not working as expected

I am working on AngularJS 1.6 version. In my app.controller.js I have added three event listeners and attached a deleteStudent method.

window.addEventListener('beforeunload', this.deleteStudent, false);
    window.addEventListener(
      'unload',
      () => {
        this.deleteStudent
      },
      false
    );
    window.addEventListener('pagehide', this.deleteStudent, false);

deleteStudent() {
 let Url = "http://localhost:9000/students/3";
    const deleteMethod = {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json'
      },
      keepalive: true
    };
    fetch(Url, deleteMethod);
}

The API call is not reaching backend but getting listed on the chrome network tab as pending state.

*The above used delete API is created in Node js and working fine with postman.

I have to call this API at the time of page unload only, where it is recommended to use either fetch API with keep-alive property true or use sendBeacon(), but my backend API is of type DELETE therefore I can not use sendBeacon() as it only supports POST.

like image 855
Akshay Avatar asked Sep 05 '25 01:09

Akshay


1 Answers

I had the same issue. Fetch API with keepalive worked well on Chrome, but it was very unreliable on Firefox. The request did not reach the server most of the time.

As a hack, I had to use the following code after calling the Fetch API to delay window close/refresh by 0.5 seconds:

beforeUnloadHandler() {
    fetch(`http://localhost:8080/api', {
    keepalive: true,
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`,
    },
    body: JSON.stringify(payload),
  });
    const time = Date.now();
    while ((Date.now() - time) < 500) {

    }
    return true;
  }

And yes, I do realize that this code is ugly. But desperate times!!!

like image 62
Pratik Joshi Avatar answered Sep 08 '25 00:09

Pratik Joshi