Fetch Keep Alive 未按预期工作

Aks*_*hay 3 onbeforeunload onunload angularjs fetch-api

我正在开发 AngularJS 1.6 版本。在我的 app.controller.js 中,我添加了三个事件侦听器并附加了一个 deleteStudent 方法。

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);
}
Run Code Online (Sandbox Code Playgroud)

API 调用未到达后端,但在 Chrome 网络选项卡上列为待处理状态。

*上面使用的删除 API 是在 Node js 中创建的,并且与 postman 一起工作正常。

我必须仅在页面卸载时调用此 API,建议使用具有keep-alive属性true的 fetch API 或使用 sendBeacon(),但我的后端 API 是DELETE类型,因此我不能使用 sendBeacon( ),因为它只支持 POST。

小智 6

我遇到过同样的问题。带 keepalive 的 Fetch API 在 Chrome 上运行良好,但在 Firefox 上非常不可靠。大多数时候请求没有到达服务器。

作为一种 hack,我必须在调用 Fetch API 后使用以下代码来延迟窗口关闭/刷新 0.5 秒:

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;
  }
Run Code Online (Sandbox Code Playgroud)

是的,我确实意识到这段代码很丑陋。但绝望的时候!!!