我正在设置一个新的VueJS项目,并在我的渐进式Web应用程序中实现了一个workbox-backgroundSync。要测试此工作箱插件,我需要断开设备(chrome)与互联网的连接并触发POST请求。在chrome下,即使没有互联网连接,此请求也要等待几分钟。因此,我的应用程序正在等待请求响应。
我的POST请求:
axios
.post('/createrecipe', recipe)
.then(response => {
commit('createRecipes', recipes);
commit('setSnackbar', { text: "Recipe was created. ( " + response.data.status + response.status + " )", color:'success', snack:true });
console.log("Response from Server for create Recipe: ", response);
})
.catch(error => {
commit('setSnackbar', { text: "Your Post will be stored and send by Internet-Connection", color: 'warning', snack: true });
console.log(error)
});
我的ServiceWorker:
const matchCb = ({url, event}) => {
return (url.pathname === '/api/createrecipe');
};
const bgSyncPlugin = new workbox.backgroundSync.Plugin('createdRecipes-post-storage-offline', {
maxRetentionTime: 24 * 60, // Retry for max of 24 Hours
});
workbox.routing.registerRoute(
matchCb,
workbox.strategies.networkOnly({
plugins: [bgSyncPlugin]
}),
'POST'
);
我在网络选项卡下的Chrome-devtool中中断了网络,后台进程成功完成。但这对用户来说不是最佳解决方案,因为他们不知道如何控制devtool。
我希望该请求将被取消,而chrome没有互联网连接。
以下是处于等待状态而不是失败状态的请求的屏幕截图:
侧面说明:我的Web应用程序在localhost下运行。
答案 0 :(得分:1)
这不是最佳解决方案,但我的伴侣Ilja KO找到了解决方法。我只是用axios实例设置了一个超时来中止请求,即使chrome是否连接了互联网。
axios.defaults.timeout = 5000;