设置服务人员仅排除某些网址 [英] Setting service worker to exclude certain urls only

查看:58
本文介绍了设置服务人员仅排除某些网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用create react构建了一个应用程序,默认情况下,该应用程序包括服务工作者。我希望只要有人输入给定的URL即可运行该应用程序,除非他们进入/ blog /(该服务提供一组静态内容)。我在应用程序中使用React Router来捕获不同的URL。

I built an app using create react which by default includes a service worker. I want the app to be run anytime someone enters the given url except when they go to /blog/, which is serving a set of static content. I use react router in the app to catch different urls.

我有nginx设置来提供/ blog /服务,如果有人访问/ blog /而没有访问react的话,效果很好应用优先。但是,由于服务人员的范围是./,因此只要有人访问除/ blog /以外的其他网址,应用程序就会加载服务人员。从那时起,服务工作者将绕过与服务器的连接,并/ blog /加载react应用而不是静态内容。

I have nginx setup to serve /blog/ and it works fine if someone visits /blog/ without visiting the react app first. However because the service worker has a scope of ./, anytime someone visits any url other than /blog/, the app loads the service worker. From that point on, the service worker bypasses a connection to the server and /blog/ loads the react app instead of the static contents.

有没有办法让服务工作者是否在/ blog /以外的所有URL上加载?

Is there a way to have the service worker load on all urls except /blog/?

推荐答案

因此,考虑到您尚未发布任何与服务人员相关的代码,可以考虑添加一个简单的 if 有条件地在代码块内进行获取

So, considering, you have not posted any code relevant to the service worker, you might consider adding a simple if conditional inside the code block for fetch

此代码块应只需添加条件

This code block should already be there inside your service worker.Just add the conditionals

self.addEventListener( 'fetch', function ( event ) {

    if ( event.request.url.match( '^.*(\/blog\/).*$' ) ) {
        return false;
    }
     // OR

    if ( event.request.url.indexOf( '/blog/' ) !== -1 ) {
        return false;
    }
    //    **** rest of your service worker code ****

请注意,您既可以使用正则表达式也可以使用原型方法 indexOf 。根据您的想法,

note you can either use the regex or the prototype method indexOf. per your whim.

以上内容将指导您的服务人员,当URL匹配 / blog /

the above would direct your service worker, to just do nothing when the url matches /blog/

这篇关于设置服务人员仅排除某些网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆