首页 > 解决方案 > Workbox BackgroundSyncPlugin _ 失败的请求 _ 通知

问题描述

我有一个工作正常的 pwa。我用工作箱做的。但我想尝试一些东西。我想在以下情况下推送通知:请求(在 IndexeDB 中持有 -> 感谢 BackgroundSyncPlugin )有错误(如 Error 500 )。请求发送,不是BackgroundSyncPlugin 的问题,而是我的HTTP 请求的问题。我想警告用户该请求无效

这是我的服务人员的一部分:

const bgSyncPlugin = new BackgroundSyncPlugin('myQueueName', {
    maxRetentionTime: 0.1 * 60, // mins,
    onSync: async({ queue }) => {
        let entry;
        while ((entry = await queue.shiftRequest())) {
            try {
                await fetch(entry.request);
                console.error("Replay successful for request", entry.request);
            } catch (error) {
                console.error("Replay failed for request", entry.request, error);

                // Put the entry back in the queue and re-throw the error:
                await queue.unshiftRequest(entry);
                throw error;
            }
        }
        console.log("Replay complete!");
        showNotification();
    }
});


registerRoute(
    /http:\/\/localhost:8000/,
    new NetworkFirst({
        plugins: [bgSyncPlugin]
    }),
    'POST'
);

我只想知道我的请求的状态码任何帮助:)

编辑:我想在标题2中获取正文

标签: http-headersprogressive-web-appsservice-workerbackgroundworkerworkbox

解决方案


您应该能够更改此行:

await fetch(entry.request);

const response = await fetch(entry.request);
// Check response.status, and do something, e.g. throw an
// Error when it's above 500:
if (response.status > 500) {
  // Throwing an Error will trigger a retry.
  throw new Error('Status: ' + response.status);
}

// This assumes that your response from the server is JSON,
// and has an error field which might be set if the request
// failed for some reason, regardless of the HTTP status code.
const responseJSON = await response.json();
if (responseJSON.error) {
  throw new Error('Failed request: ' + responseJSON.error);
}

推荐阅读