Service Worker 发送了重复的 post 请求

Duplicate post request sent by Service Worker

我刚刚发现这个问题是因为我在使用 workbox-background-sync 时试图解决重复的 post 请求问题。我的网络应用程序具有上传照片的功能。但是每次我确实上传了两次到数据库。这是我的代码:

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 .

我终于找到了解决办法。下面是我的代码:

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 and two。不再有重复的帖子。