问题描述
我有一个工作正常的 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'
);
我只想知道我的请求的状态码 任何帮助:)
编辑:我想得到 Body in header2
解决方法
您应该能够更改此行:
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);
}