如何在服务工作者内部监听请求中止事件?

huangapple go评论80阅读模式
英文:

How can I listen to a request abort event inside a service-worker?

问题

我正在使用 Axios 和 React 在 PWA 中获取一些数据。我已经编写了中止控制器来在第一次调用仍在进行中时中止调用相同的API。

虽然从应用程序到服务工作线程的调用定期取消,但从服务工作线程到服务器的调用始终被满足。

以下是一个示例:

// 应用程序
useEffect(() => {
  const controller = new AbortController();

  axios.get<any, IInstance[]>('/instances',
    { signal: controller.signal })
    .then(data => setInstancesState(data));

  return () => {
    controller.abort();
  };
}, [foo]);

// 服务工作线程
self.addEventListener("fetch", (event) => {
  const url = (new URL(event.request.url));
  console.log(event.request.signal.aborted); // 始终为 false
  event.respondWith(fetch(event.request));
});

我如何拦截应用程序到服务工作线程的请求中止?

英文:

I'm fetching some data with Axios and React inside a PWA. I programmed the abort-controller to abort calls if the same API is called twice while the first call is still in progress.

While the calls from the app to the service worker are regularly cancelled, the calls from service-worker to server are always fulfilled.

Here's an example:

 // app
  useEffect(() =&gt; {
    const controller = new AbortController();

    axios.get&lt;any, IInstance[]&gt;(&#39;/instances&#39;,
      { signal: controller.signal })
      .then(data =&gt; setInstancesState(data));

    return () =&gt; {
      controller.abort();
    };
  }, [foo]);

// service-worker
self.addEventListener(&quot;fetch&quot;, (event) =&gt; {
  const url = (new URL(event.request.url));
  console.log(event.request.signal.aborted); // Always false
  event.respondWith(fetch(event.request));
});

How can I intercept the request abortion from the app to the service-worker?

答案1

得分: 1

Axios使用XHR请求。确保XHR请求能够与所有浏览器进行拦截。

Service Workers能够响应同步XHR请求吗?

而且,我 强烈 推荐在ReactQuery中使用Axios。

关于服务工作者中的中止请求,我必须提到它由useEffect中的AbortController实例控制,而不是在请求中。

您必须使用 addEventListener('abort', (event) => { }) 或使用您自己的实例。但在serviceWorker中都无法访问它们。

获取更多信息,请阅读:

abort事件

aborted属性

英文:

Axios makes XHR requests. Make sure XHR requests can intercept with all browsers.

Can Service Workers respond to synchronous XHR requests?

And I highly recommend using Axios with ReactQuery.

About the abort request in the service worker, I have to mention that it's controlled by an instance of AbortController in the useEffect, not in request.

You have to use addEventListener(&#39;abort&#39;, (event) =&gt; { }) or use your instance. But none of them are accessible in serviceWorker.

For more information, read:

abort event

aborted property

huangapple
  • 本文由 发表于 2023年6月12日 22:28:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76457650.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定