【问题标题】:How to make Axios use Fetch instead of XMLHttpRequest如何让 Axios 使用 Fetch 而不是 XMLHttpRequest
【发布时间】:2019-06-12 13:00:01
【问题描述】:

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

我为 service worker 和 vue cli 使用 workbox。 我的 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和图像文件缓存良好

【问题讨论】:

  • 答案对您有用吗?虽然我同意协议必须是 https 才能使用 Service Worker,但 XMLHttpRequest 也可能是原因。实际上我遇到了同样的问题,就我而言,需要将XMLHttpRequest 替换为fetch 以使其离线工作。

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-10-20
    • 2021-01-11
    • 2023-03-16
    • 2021-05-18
    • 2019-07-18
    • 1970-01-01
    • 2022-11-16
    • 2019-03-10
    • 2018-04-22
    相关资源
    最近更新 更多