如何使Axios使用Fetch而不是XMLHttpRequest

时间:2019-01-18 09:26:38

标签: xmlhttprequest axios progressive-web-apps vue-cli

我是PWA的初学者,我尝试获取代码来调用API,然后将其存储在浏览器的缓存中。但是我看到axios使用XMLHttpRequest而不是fetch API,因此无法缓存我的API调用。

我将工作箱用于服务人员和vue cli。 我的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,
        }),
      ],
    }),
  );

我的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)
    }
  })
}

和我的呼叫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);
        });

    }
}

我认为这确实是xmlhttprequest的故事,但我不确定。 另一方面,js,css和images文件也得到了很好的缓存

1 个答案:

答案 0 :(得分:1)

您在服务工作者中使用的RegExp路由会寻找http://api.giphy.com/v1/gifs/,这是一个http: URL。服务人员将仅拦截安全请求,这意味着https:(或http://localhost)。

确保在客户端Vue代码中使用https:,并调整Workbox配置以同时使用https: