Cloudflare service worker code to “Bypass cache on cookie” not working

匿名 (未验证) 提交于 2019-12-03 01:37:02

问题:

I wrote this code as a Cloudflare Service Worker which is meant to precisely emulate their native function for "Bypass cache on cookie". Specifically, if someone has a Wordpress cookie - it would bypass cache, otherwise it does not.

It does not seem to function at all - in that despite having a cookie and being logged in (confirmed via Chrome developer tools) - I still get a Cloudflare cache HIT on this example domain - Tallyfy. Anything wrong with it? Help appreciated!

// A Service Worker which skips cache if the request contains a cookie. addEventListener('fetch', event => { let request = event.request;  var flag=false; if(request.headers.cookie)   {  var pairs = request.headers.cookie.split(";"); var patt = new RegExp("wp-.*|wordpress.*|comment_.*|woocommerce_.*")   for(var i=0;i<pairs.length;i++){   if(patt.test(pairs[i])){       flag = true;       break;   } }  }    if (request.headers.has('Cookie') && flag) {     // Cookie present. Add Cache-Control: no-cache.     let newHeaders = new Headers(request.headers)     newHeaders.set('Cache-Control', 'no-cache')     event.respondWith(fetch(request, {headers: newHeaders}))   }   // Use default behavior.   return })

回答1:

try this and let me know

addEventListener('fetch', event => {   let request = event.request   var flag = false;   if (request.headers.has('Cookie')) {     var cookie = request.headers.get('Cookie');     pairs = cookie.split(";");     var patt = new RegExp("wordpress_logged_in.*|wp_woocommerce_session.*");     for(var i=0;i<pairs.length;i++){       if(patt.test(pairs[i])){           flag = true;           break;       }     }     console.log(flag);     if (request.headers.has('Cookie') && flag) {       let newHeaders = new Headers(request.headers)       newHeaders.set('Cache-Control', 'no-cache')       newHeaders.set('Pragma', 'no-cache')       event.respondWith(fetch(request, {headers: newHeaders}))     }     // Use default behavior.     return;   } })


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!