我刚发现此问题是因为我在尝试使用workbox-background-sync时试图解决重复的发帖请求问题。我的网络应用程序具有上传照片的功能。但是每次我上载两次到数据库。这是我的代码:
const bgSyncQueue = new workbox.backgroundSync.Queue(
'photoSubmissions',
{
maxRetentionTime: 48 * 60,//48 hours
callbacks: {
queueDidReplay: function (requests) {
if (requests.length === 0) {
removeAllPhotoSubmissions();
}
else {
for(let request of requests) {
if (request.error === undefined && (request.response && request.response.status === 200)) {
removePhotoSubmission();
}
}
}
}
}
});
workbox.routing.registerRoute(
new RegExp('.*\/Home\/Submit'),
args => {
const promiseChain = fetch(args.event.request.clone())
.catch(err => {
bgSyncQueue.addRequest(args.event.request);
addPhotoSubmission();
changePhoto();
});
event.waitUntil(promiseChain);
},
'POST'
);
可能是因为fetch(args.event.request.clone())
。如果我将其删除,则不再有重复。我正在使用3.6.1版工作箱。
答案 0 :(得分:1)
最后我找到了解决方案。下面是我的代码:
const photoQueue = new workbox.backgroundSync.Plugin('photoSubmissions', {
maxRetentionTime: 48 * 60, // Retry for max of 48 Hours
callbacks: {
queueDidReplay: function (requests) {
if (requests.length === 0) {
removeAllPhotoSubmissions();
}
else {
for(let request of requests) {
if (request.error === undefined && (request.response && request.response.status === 200)) {
removePhotoSubmission();
}
}
}
}
}
});
const myPhotoPlugin = {
fetchDidFail: async ({originalRequest, request, error, event}) => {
addPhotoSubmission();
changePhoto();
}
};
workbox.routing.registerRoute(
new RegExp('.*\/Home\/Submit'),
workbox.strategies.networkOnly({
plugins: [
photoQueue,
myPhotoPlugin
]
}),
'POST'
);
我删除了fetch
。如果我们仍然想自己控制,则需要使用respondWith()
。我已经测试过了,它正在工作。但是我想使用更多的工作箱方式来解决问题。我使用的是Workbox 3.6.3,并创建了自己的插件以包含回调函数fetchDidFail
以更新我的视图。这是我找到的参考:
one和two。没有重复的帖子了。