【问题标题】:How to return blob item from localForage in service worker?如何从服务工作者的 localForage 返回 blob 项目?
【发布时间】:2021-10-26 08:32:11
【问题描述】:

在我的服务人员中,我将 mp4 视频存储在 indexedDB 中,并在 blob 数据中使用 localforage 库。是工作 !但我不知道如何返回这个 blob 数据。

这是我的 fetchHandler 代码:

const fetchHandler = async (event) => {
    const getResponse = async () => {
        const request = event.request;
        if( request.destination === 'video' ){
            // Get from indexedDB
            const value = await localforage.getItem('video');
            // How return the video from indexedDB cache ?
            if( value ) return value; // not working
            // Add in indexedDB
            var networkResponse = await fetch(event.request);
            localforage.setItem('video', networkResponse.blob() ).then(function (value) {
                // Do other things once the value has been saved.
                console.log(value);
            }).catch(function(err) {
                // This code runs if there were any errors
                console.log(err);
            });
        }else{
            const openedCache = await caches.open(SW_CACHE_NAME);
            const cacheResponse = await openedCache.match(request);
            if (cacheResponse) return cacheResponse;

            var networkResponse = await fetch(event.request);
            const cachePutResponse = await openedCache.put(request, networkResponse.clone());
            if (cachePutResponse) return cachePutResponse;
        }

        return networkResponse;
    };
    event.respondWith(getResponse());
};

感谢您的帮助

【问题讨论】:

    标签: blob service-worker indexeddb localforage


    【解决方案1】:

    您需要将有效的Response 对象传递给event.respondWith()。这需要一个响应正文(这是您从localforeage.getItem() 返回的内容),还需要一些响应标头。

    您可以使用 Response constructor 创建它,然后从您的 getResponse() 函数中返回它。

    代码可能类似于:

    const value = await localforage.getItem('video');
    if (value) {
      // See https://fetch.spec.whatwg.org/#bodyinit for what's accepted
      // as a BodyInit.
      return new Response(value, {
        headers: {
          // Replace this with the actual MIME type for the video.
          'content-type': 'video/mp4',
          // Include any other headers here if desired.
        }
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 2016-01-10
      • 2012-02-29
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      相关资源
      最近更新 更多