我只是在 google chrome 中尝试 service workers。我偶然发现了一个错误。 Googling the error gives one single result目前似乎在google chrome sourcecode .
我不相信错误是bug。当我在 firefox 中尝试时,出现内容损坏错误屏幕。它发生在我处理项目根目录的获取事件时:
self.addEventListener('fetch', function(event) {
// Nice url
var requestURL = new URL(event.request.url);
console.log("Request for: ", requestURL.href);
// Network, then cache, then fallback
event.respondWith(
// Try to download
fetch(event.request)
.then(function(x) {
console.log(" "+requestURL.href+" >> ",x);
// If failed the x will not be ok
if(x && x.ok) {
// If result was ok save it to cache
cache.put(event.request, x);
return x;
}
else
// Try to fetch cached version if request failed
return cache.match(event.request);
})
// In case of error return something like 404 page
.catch(function(error) {
console.warn(" "+requestURL.href+" >> UNAVAILABLE: ",error);
return cache.match('/page/content-not-available-offline');
})
);
});
我不确定 body locked 错误是什么意思,所以我什至不知道相关代码是什么。
最佳答案
问题是响应的 body
(实际内容,例如 HTML 或 JavaScript)只能用于某些目的一次,例如保存到缓存中或用作实际响应。
要解决这个问题,Response.prototype.clone()
方法存在。
In fact, the main reason
clone()
exists is to allow multiple uses ofBody
objects (when they are one-use only.)
在这种情况下,问题在于将响应存储在缓存中然后将其返回。正确的做法是:
if(x && x.ok) {
// If result was ok save it to cache
cache.put(event.request, x.clone());
return x;
}
关于javascript - "body"被锁定的响应不能用于响应请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37747332/