I am beginner in the PWA and I try to get my code to call an API and then store it in the browser's cache. But I see that axios uses the XMLHttpRequest and not the fetch API, so I can't cache my API call.
I use workbox for the service worker and vue cli. my service-worker.js :
workbox.setConfig({
debug: false,
});
workbox.precaching.precacheAndRoute([]);
//image in cache
workbox.routing.registerRoute(
/\.(?:png|gif|jpg|jpeg|svg)$/,
workbox.strategies.staleWhileRevalidate({
cacheName: 'images',
plugins: [
new workbox.expiration.Plugin({
maxEntries: 60,
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
}),
],
}),
);
//network request in cache
workbox.routing.registerRoute(
new RegExp('http://api.giphy.com/v1/gifs/'),
workbox.strategies.networkFirst({
cacheName: 'api',
}),
);
//js and css in cache
workbox.routing.registerRoute(
/\.(?:js|css)$/,
workbox.strategies.staleWhileRevalidate(),
);
//webfont in cache
workbox.routing.registerRoute(
new RegExp('https://fonts.(?:googleapis|gstatic).com/(.*)'),
workbox.strategies.cacheFirst({
cacheName: 'googleapis',
plugins: [
new workbox.expiration.Plugin({
maxEntries: 30,
}),
],
}),
);
my registerServiceWorker.js :
import { register } from 'register-service-worker'
if (process.env.NODE_ENV === 'production') {
register(`${process.env.BASE_URL}service-worker.js`, {
ready () {
console.log(
'App is being served from cache by a service worker.\n'
)
},
registered () {
console.log('Service worker has been registered.')
},
cached () {
console.log('content in cached');
},
updatefound () {
console.log('New content is downloading.')
},
updated () {
console.log('New content is available; please refresh.')
},
offline () {
},
error (error) {
console.error('Error during service worker registration:', error)
}
})
}
and my call API :
import Vue from 'vue';
import CONSTANTS from '../constants/constants';
import exception_manager from 'exception_manager';
export default {
getGiphy() {
return Vue.axios.get(`${CONSTANTS.SERVER_ADDRESS}search?q=cat&api_key=${CONSTANTS.API_KEY}&limit=9`).catch(error => {
exception_manager.handleException(error, 'GiphyService.js', 8, window, CONSTANTS.ERROR_SERVER_ADDRESS);
});
}
}
I think that's really the story with the xmlhttprequest, but I'm not sure. On the other hand, js, css and images files are well cached
Your RegExp route inside of the service worker looks for http://api.giphy.com/v1/gifs/
, which is an http:
URL. Service workers will only intercept secure requests, which means https:
(or http://localhost
).
Make sure that you're using https:
in your client-side Vue code, and adjust your Workbox configuration to use https:
as well.