2
我正在構建一個Web應用程序,我需要離線存儲數據。爲此我使用了indexedDb。我想將從API接收到的響應存儲到indexedDB中,然後將這些數據傳遞給Web應用程序。在IndexedDB中存儲API響應
我該如何做到這一點?我已經瀏覽了官方Docs,但沒有提及如何將api響應數據傳遞給indexedDB。
我正在構建一個Web應用程序,我需要離線存儲數據。爲此我使用了indexedDb。我想將從API接收到的響應存儲到indexedDB中,然後將這些數據傳遞給Web應用程序。在IndexedDB中存儲API響應
我該如何做到這一點?我已經瀏覽了官方Docs,但沒有提及如何將api響應數據傳遞給indexedDB。
我將響應轉換爲blob,然後將該blob存儲在indexeddb中。查看完整的頁面here:
return fetch(new Request(prefetchThisUrl, { mode: 'no-cors' }))
.then((resp) => {
resp.blob()
.then((blob) => {
console.log(`blob is: ${blob.size}, ${blob.type}`);
return db.set(prefetchThisUrl, blob);
});
});
然後,您可以從索引資料檢索它在後續請求
db.get(event.request.url).then((blobFound) => {
if (!blobFound) {
console.error(`error in retrieving from db: ${blobFound}`);
return fetch(event.request.clone())
.then((response) => {
// only cache valid responses
if (!response) {
console.error(`received invalid response from fetch: ${responseTwo}`);
return resolve(response);
}
// insert response body in db
response.clone().blob().then(
(blob) => {
console.info(`updating cache with: ${JSON.stringify(event.request.clone().url)}, then returning`);
db.set(
event.request.url,
blob
).then(
(suc2) => console.log(`success in setting: ${suc2}`),
(err2) => console.error(`error in setting: ${err2}`)
);
}
);
return resolve(response);
});
}
const contentType = consts.getBlobType(blobFound, event.request.url);
console.log('responding from cache', event.request.url, contentType);
// on this page https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
const myHeaders = new Headers({
"Content-Length": String(blobFound.size),
"Content-Type": contentType,
"X-Custom-Header": "ProcessThisImmediately",
});
const init = {
'content-type': 'text/html; charset=utf-8',
'headers': myHeaders,
'status' : 200,
'statusText' : 'OKS',
};
const response = new Response(blobFound, init);
return resolve(response);
});
}));
我在與存儲圖像的特定問題,例如https://travis-ci.org/noahehall/udacity-trainschedule.svg?branch=master – neh