我使用Backbone.js构建了一个Web应用程序,它有很多调用RESTful服务,它就像一个魅力。
我尝试添加ServiceWorker来缓存之前的所有通话,以便他们可以脱机使用。
我实际上得到的是我第一次做的调用因这个错误而死:
无法加载资源:net :: ERR_FAILED
然而,在页面重新加载时,我得到了它的缓存数据
我的服务工作人员获取:
var elements = document.getElementsByTagName('span');
for(var i=elements.length-1;i>0;i--)
elements[i].parentNode.removeChild(elements[i]);
编辑:
我不认为需要任何Backbone.js网络应用程序代码。
我使用Backbone.js模型和集合中的self.addEventListener('fetch', function(e) {
// e.respondWidth Responds to the fetch event
e.respondWith(
// Check in cache for the request being made
caches.match(e.request)
.then(function(response) {
// If the request is in the cache
if ( response ) {
console.log("[ServiceWorker] Found in Cache", e.request.url, response);
// Return the cached version
return response;
}
// If the request is NOT in the cache, fetch and cache
var requestClone = e.request.clone();
fetch(requestClone)
.then(function(response) {
if ( !response ) {
console.log("[ServiceWorker] No response from fetch ")
return response;
}
var responseClone = response.clone();
// Open the cache
caches.open(cacheName).then(function(cache) {
// Put the fetched response in the cache
cache.put(e.request, responseClone);
console.log('[ServiceWorker] New Data Cached', e.request.url);
// Return the response
return response;
}); // end caches.open
console.log("Response is.. ?", response)
return response;
})
.catch(function(err) {
console.log('[ServiceWorker] Error Fetching & Caching New Data', err);
});
}) // end caches.match(e.request)
); // end e.respondWith
});
方法。
打电话
https://jsonplaceholder.typicode.com/posts/1
和
https://jsonplaceholder.typicode.com/posts/2
将重播第一次显示此错误。刷新页面后,我确实没有请求此信息。全部来自缓存。 以及我仍然没有做的所有其他请求,将保持错误
答案 0 :(得分:0)
我看到的唯一问题是,当请求不在缓存中时,您执行了fetch
,但是您没有返回 fetch
的结果到封闭的then
处理程序。您需要添加return
才能拥有:
return fetch(requestClone)
.then(function(response) {
return
处理程序中then
处理程序中fetch
语句提供的所有数据都不会被转移到链上。
我也看到你没有回复caches.open(cacheName).then...
提供的承诺。如果您希望将缓存中的响应保存到链中返回结果,那么可能可以正常,但至少我会发表评论说这就是我在这里做的而不是留给读者去弄清楚return
陈述是否偶然遗失,或者是故意的。
答案 1 :(得分:0)
我搜索了更多后解决了它。 Backbone.js我以前在Web应用程序中的观点:
this.listenTo(this.collection,"reset",this.render);
this.listenTo(this.collection,"add",this.addCollectionItem);
this.listenTo(this.collection,"error", this.errorRender);
而我的服务工作人员正在返回Promises。
我不得不将我的一些代码更改为我的Web应用程序视图:
this.collection.fetch({},{reset:true})
.then(_.bind(this.render, this))
.fail(_.bind(this.errorRender,this))
或多或少......