如何让 Axios 使用 Fetch 而不是 XMLHttpRequest

How to make Axios use Fetch instead of XMLHttpRequest

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

我将 workbox 用于 service worker 和 vue cli。 我的服务-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和图片文件都缓存的很好

Service Worker 内部的 RegExp 路由查找 http://api.giphy.com/v1/gifs/,这是一个 http: URL。 Service Worker 只会拦截安全请求,这意味着 https:(或 http://localhost)。

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