"body" 被锁定的响应不能用于响应请求
Response whose "body" is locked cannot be used to respond to a request
我只是在 google chrome 中尝试 service workers。我偶然发现了一个错误。 Googling the error gives one single result at the moment which seems to be in the google chrome sourcecode.
我不相信这个错误是bug。当我在 firefox 中尝试时,出现 Corrupted Content Error 屏幕。当我处理项目根的获取事件时发生:
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 of Body
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;
}
我只是在 google chrome 中尝试 service workers。我偶然发现了一个错误。 Googling the error gives one single result at the moment which seems to be in the google chrome sourcecode.
我不相信这个错误是bug。当我在 firefox 中尝试时,出现 Corrupted Content Error 屏幕。当我处理项目根的获取事件时发生:
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;
}