英文:
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(() => {
const controller = new AbortController();
axios.get<any, IInstance[]>('/instances',
{ signal: controller.signal })
.then(data => setInstancesState(data));
return () => {
controller.abort();
};
}, [foo]);
// service-worker
self.addEventListener("fetch", (event) => {
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请求能够与所有浏览器进行拦截。
而且,我 强烈 推荐在ReactQuery中使用Axios。
关于服务工作者中的中止请求,我必须提到它由useEffect中的AbortController实例控制,而不是在请求中。
您必须使用 addEventListener('abort', (event) => { })
或使用您自己的实例。但在serviceWorker中都无法访问它们。
获取更多信息,请阅读:
英文:
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('abort', (event) => { })
or use your instance. But none of them are accessible in serviceWorker.
For more information, read:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论