Работник сервиса не создает сеть First Cache - PullRequest
0 голосов
/ 12 декабря 2018

My Service Worker:

importScripts('https://storage.googleapis.com/workbox- 
cdn/releases/3.0.0/workbox-sw.js');

//Use Workbox Precache for our static Assets

workbox.precaching.precacheAndRoute([]);
console.log('this is my custom service worker');


//Create articles Cache from online resources
const onlineResources = workbox.strategies.networkFirst({
cacheName: 'articles-cache',
plugins: [
  new workbox.expiration.Plugin({
    maxEntries: 50,
    }),
   ],
  });


workbox.routing.registerRoute('https://newsapi.org/(.*)', args => {
return onlineResources.handle(args);
 });

Кэш предварительного кэша работает, но кэш online-ресурсов никогда не создается.

Посмотрите на мою файловую структуру:

enter image description here

Так что я не думаю, что область действия - это проблема, хотя я не вижу клиентов в своем сервисном работнике на инструментах разработчика Chrome.

Наконец, вот мой app.jsfile:

    //main populates main tags in indexpage
const main  = document.querySelector('main');
//this populates the source dropdown menu with sources
const sourceSelector = document.querySelector('#sourceSelector');
//set default source so page loads this
const defaultSource = 'bbc-news';

//on window load call update news and when update
window.addEventListener('load', async e => {
    updateNews();
   await updateSources();
   sourceSelector.value = defaultSource;

   //when sourceSelector is changed update the news with the new source
   sourceSelector.addEventListener('change',e =>{
       updateNews(e.target.value);
   });



//checks for serviceWorker in browser
if('serviceWorker'in navigator){
    try{
        //if there is register it from a path
        navigator.serviceWorker.register('/sw.js');
        console.log('registered!');
        }  catch(error){
        console.log('no register!',error);
    }
}
});



async function updateNews(source= defaultSource){
//response awaits a fetch of the news API call
const res = await fetch(`https://newsapi.org/v2/top-headlines?sources=${source}&apiKey=82b0c1e5744542bdb8c02b61d6499d8f`);
const json = await res.json();

//fill the html with the retrieved json articles
main.innerHTML = json.articles.map(createArticle).join('\n');
}


//Update the news source
async function updateSources(){

    const res = await fetch(`https://newsapi.org/v2/sources?apiKey=82b0c1e5744542bdb8c02b61d6499d8f`);
    const json = await res.json();

    //Whatever source the sourceSelector picks gets mapped and we take the id of it - It is used with updateNews();
    sourceSelector.innerHTML = json.sources
    .map(src=>`<option value="${src.id}">${src.name}</option>`).join('\n');
    }







function createArticle(article){
    return `     <div class="article">
        <a href="${article.url}">
        <h2>${article.title}</h2>
        <img src="${article.urlToImage}">
        <p>${article.description}</p>
        </a>
        </div>
    `;
}

App.js подключается к newsAPI и выводит JSON на страницы HTML.

1 Ответ

0 голосов
/ 10 января 2019

Когда вы регистрируете маршрут, вы, кажется, пытаетесь использовать регулярное выражение в качестве строки.Я думаю, что это буквально интерпретирует маршрут как строку, которая включает .*.Вместо этого попробуйте регулярное выражение /^https:\/\/newsapi\.org/, которое согласно документам будет совпадать с начала URL.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...