簡體   English   中英

始終使用index.html進行響應

[英]Respond always with index.html

React app(通常)對所有URL使用相同的index.html ,這就是我的服務器響應的內容。

但是,第一個請求絕不是 example.com/index.html ,例如example.com/example.com/posts / example.com/post/123example.com/contact example.com/ / example.com/postsexample.com/post/123 / example.com/contact等等。

如果我從Chrome DevTools打開離線模式,我只會獲得默認的無連接頁面。

如何始終從緩存中回復index.html


相關代碼:

self.addEventListener('install', function(e) {
    self.skipWaiting()

    e.waitUntil(
        caches.open('v1').then(function(cache) {
            return cache.addAll([
                'index.html',
                'main.js',
                'main.css'
            ])
        })
    )
})

self.addEventListener('fetch', function(e) {
    e.respondWith(
        caches.match(e.request).then(function(match) {
            // If no match in cache, send request
            return match || fetch(e.request)
        })
    )
})

我使用localhost但我找不到任何關於這個問題的重要信息。

這是因為你明確地試圖只從緩存中打開緩存命中( caches.match(e.request).then ...在你的fetch監聽器中)。 因此它只會匹配您手動添加到緩存的URL。

要使用預緩存值響應所有請求,您需要顯式查找index.html緩存條目,如下所示:

self.addEventListener('fetch', function(e) {
    var indexRequest = new Request('/index.html');

    // route index.html-based URLs to the specific cache directly
    if (shouldRespondWithIndex(e.request.url)) {
        e.respondWith(caches.match(indexRequest))
    } else {
        // other URLs may go through the standard "look for exact match
        // in the cache with network fallback" route
        e.respondWith(
            caches.match(e.request).then(function(match) {
                // If no match in cache, send request
                return match || fetch(e.request)
            }))
    }
})

請注意,您的shouldRespondWithIndex實現應該對所有非文檔請求(即圖像,樣式表等)返回false ,否則Service Worker也會將其替換為index.html

您需要更改代碼的這一部分:

caches.match(e.request).then(function(match) {
    // If no match in cache, send request
    return match || fetch(e.request)
})

根據您需要的條件返回index.html。 您可以在緩存文檔中找到更多信息。

https://developer.mozilla.org/en-US/docs/Web/API/Cache

要響應訪問者並避免脫機屏幕,您必須決定如何處理的部分是如何檢查event.request以查看返回index.html是否良好,否則它可能會返回,即使您不想。 您必須使用event.respondWith,手動打開緩存,找到所需的緩存元素並將其返回。 因此,不要尋找與event.request的匹配,而是像這樣找到與index.html的匹配:

  event.respondWith(

    // Opens Cache objects that start with 'font'.
    caches.open(CURRENT_CACHES['font']).then(function(cache) {
      return cache.match('/index.html').then(function(response) {
        if (response) {
          console.log(' Found response in cache:', response);

          return response;
        } 
      }).catch(function(error) {

        // Handles exceptions that arise from match() or fetch().
        console.error('  Error in fetch handler:', error);

        throw error;
      });
    })
  );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM