我认为这会相当简单,但我很难成功发送响应,然后修改存储在服务工作线程内的缓存中的克隆响应。
最终我想在缓存的数据中附加获取的时间和日期。我正在使用我的服务工作人员首先从网络获取此数据,如果数据不可用,则回退到缓存。
这是我的服务人员的代码
event.respondWith(
fetch(event.request)
.then(function(e) {
console.log('response', e)
var responseToCache = e.clone();
responseToCache.json().then(function(data) {
var today = new Date();
var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
data.cached = { date: date, time: time }
return data
})
// var init = {
// status: response.status,
// statusText: response.statusText,
// headers: { 'X-Foo': 'My Custom Header' }
// };
// response.headers.forEach(function(v, k) {
// init.headers[k] = v;
// });
// var responseToCache = response.text().then(function(body) {
// var today = new Date();
// var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
// var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
// var bodyObj = JSON.parse(body)
// bodyObj.cached = { date: date, time: time }
// body = JSON.stringify(bodyObj)
// return new Response(body, init);
// });
caches.open(CACHE_NAME)
.then(function(cache) {
cache.put(requestURL, responseToCache);
});
return e
})
.catch(function() {
console.log('data offline')
return caches.match(requestURL);
})
);
像下面这样的东西应该可以工作
event.respondWith(
fetch(event.request)
.then(async function (originalResponse) {
console.log('originalResponse', originalResponse)
// consume the original response, and create a new one to return to the browser
const originalData = await originalResponse.json();
var today = new Date();
var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
const modifiedData = {
...originalData,
cached: {date: date, time: time }
}
const newResponse = new Response(JSON.stringify(originalData), {
status: originalResponse.status,
statusText: originalResponse.statusText,
headers: originalResponse.headers
});
const responseToCache = new Response(JSON.stringify(modifiedData), {
status: originalResponse.status,
statusText: originalResponse.statusText,
headers: originalResponse.headers
});
return caches.open(CACHE_NAME)
.then(function(cache) {
cache.put(requestURL, responseToCache);
return originalResponse
});
})
.catch(function() {
console.log('data offline')
return caches.match(requestURL);
})
);
它有什么作用?
基本上,您想要缓存与实际响应不同的响应,因此,创建一个新响应。请注意,我没有测试