Javascript Progressive Web App Uncaught (in promise) TypeError: Failed to fetch
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47160929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Progressive web app Uncaught (in promise) TypeError: Failed to fetch
提问by Ku3a
I started learning PWA (Progressive Web App) and I have problem, console "throws" error Uncaught (in promise) TypeError: Failed to fetch.
我开始学习 PWA(渐进式 Web 应用程序),但遇到问题,控制台“抛出”错误未捕获(承诺)类型错误:无法获取。
Anyone know what could be the cause?
有谁知道可能是什么原因?
let CACHE = 'cache';
self.addEventListener('install', function(evt) {
console.log('The service worker is being installed.');
evt.waitUntil(precache());
});
self.addEventListener('fetch', function(evt) {
console.log('The service worker is serving the asset.');
evt.respondWith(fromCache(evt.request));
});
function precache() {
return caches.open(CACHE).then(function (cache) {
return cache.addAll([
'/media/wysiwyg/homepage/desktop.jpg',
'/media/wysiwyg/homepage/bottom2_desktop.jpg'
]);
});
}
function fromCache(request) {
return caches.open(CACHE).then(function (cache) {
return cache.match(request).then(function (matching) {
return matching || Promise.reject('no-match');
});
});
}
回答by BlackBeard
I think this is due to the fact that you don't have a fallback strategy. event.respondWithcomes with a promise which you have to catch if there's some error.
我认为这是因为您没有后备策略。event.respondWith附带一个承诺,如果出现错误,您必须抓住它。
So, I'd suggest that you change your code from this:
所以,我建议你改变你的代码:
self.addEventListener('fetch', function(evt) {
console.log('The service worker is serving the asset.');
evt.respondWith(fromCache(evt.request));
});
To something like this:
对于这样的事情:
addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
if (response) {
return response; // if valid response is found in cache return it
} else {
return fetch(event.request) //fetch from internet
.then(function(res) {
return caches.open(CACHE_DYNAMIC_NAME)
.then(function(cache) {
cache.put(event.request.url, res.clone()); //save the response for future
return res; // return the fetched data
})
})
.catch(function(err) { // fallback mechanism
return caches.open(CACHE_CONTAINING_ERROR_MESSAGES)
.then(function(cache) {
return cache.match('/offline.html');
});
});
}
})
);
});
NOTE:There are many strategies for caching, what I've shown here is offline firstapproach. For more info this& thisis a must read.
回答by Hudson Moreira da Cunha
I found a solution to the same error, in my case the error showed when the service worker could not find a file*, fix it by following the network in dev tool of chrome session, and identified the nonexistent file that the service worker did not find and removed array of files to register.
我找到了相同错误的解决方案,在我的情况下,当服务工作者找不到文件时显示错误*,通过在 chrome 会话的开发工具中跟踪网络来修复它,并识别出服务工作者没有的不存在的文件查找并删除要注册的文件数组。
'/processos/themes/base/js/processos/step/Validation.min.js',
'/processos/themes/base/js/processos/Acoes.min.js',
'/processos/themes/base/js/processos/Processos.min.js',
'/processos/themes/base/js/processos/jBPM.min.js',
'/processos/themes/base/js/highcharts/highcharts-options-white.js',
'/processos/themes/base/js/publico/ProcessoJsController.js',
// '/processos/gzip_457955466/bundles/plugins.jawrjs',
// '/processos/gzip_N1378055855/bundles/publico.jawrjs',
// '/processos/gzip_457955466/bundles/plugins.jawrjs',
'/mobile/js/about.js',
'/mobile/js/access.js',
*I bolded the solution for me... I start with just a file for cache and then add another... till I get the bad path to one, also define the scope {scope: '/'} or {scope: './'} - edit by lawrghita
*我为我加粗了解决方案......我从一个缓存文件开始,然后添加另一个......直到我得到一个错误的路径,同时定义范围 {scope: '/'} 或 {scope: ' ./'} - 由 lawrghita 编辑
回答by DirtyOne
I had the same error and in my case Adblock was blocking the fetch to an url which started by 'ad' (e.g. /adsomething.php)
我遇到了同样的错误,在我的情况下,Adblock 阻止了对以“ad”开头的 url 的获取(例如 /adsomething.php)
回答by Marshall Fungai
In my case, the files to be cached were not found (check the network console), something to do with relative paths, since I am using localhost and the site is inside a sub-directory because I develop multiple projects on a XAMPP server.
就我而言,未找到要缓存的文件(检查网络控制台),这与相对路径有关,因为我使用的是 localhost,并且站点位于子目录中,因为我在 XAMPP 服务器上开发了多个项目。
So I changed
所以我改变了
let cache_name = 'Custom_name_cache';
let cached_assets = [
'/',
'index.php',
'css/main.css',
'js/main.js'
];
self.addEventListener('install', function (e) {
e.waitUntil(
caches.open(cache_name).then(function (cache) {
return cache.addAll(cached_assets);
})
);
});
To below: note the "./" on the cached_assets
到下面:注意 cached_assets 上的“./”
let cache_name = 'Custom_name_cache';
let cached_assets = [
'./',
'./index.php',
'./css/main.css',
'./js/main.js'
];
self.addEventListener('install', function (e) {
e.waitUntil(
caches.open(cache_name).then(function (cache) {
return cache.addAll(cached_assets);
})
);
});
回答by Nagibaba
Try to use /before adding or fetching any path like /offline.htmlor /main.js
/在添加或获取任何路径之前尝试使用/offline.html或/main.js

