繁体   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