【问题标题】:Vue.js cache http requests with axiosVue.js 使用 axios 缓存 http 请求
【发布时间】:2018-09-15 05:03:28
【问题描述】:

我正在使用 Vue.js 开发 PWA。 当用户启动它时,需要来自另一个应用程序的一些信息。为此,我正在使用 axios:

let url = 'url';
axios.get(url).then((response) => {
  callback(response.data)
})

只要用户在线,它就可以正常工作。如果网络连接正常,则应通过 URL 检索数据,如果没有 Internet 连接,则应从缓存中加载数据。这怎么可能?

【问题讨论】:

标签: vue.js axios


【解决方案1】:

您可以查看此扩展程序https://github.com/kuitos/axios-extensions

这里是基本用法示例,希望对你有帮助

import axios from 'axios';
import { cacheAdapterEnhancer } from 'axios-extensions';

const http = axios.create({
    baseURL: '/',
    headers: { 'Cache-Control': 'no-cache' },
    // cache will be enabled by default
    adapter: cacheAdapterEnhancer(axios.defaults.adapter)
});

http.get('/users'); // make real http request
http.get('/users'); // use the response from the cache of previous request, without real http request made
http.get('/users', { cache: false }); // disable cache manually and the the real http request invoked

【讨论】:

  • -1 此适配器库将忽略来自数据提供者的所有缓存指令,并使用消费者端配置进行缓存(默认为 5 分钟)。如果您可以控制源数据/服务,请使用适当的 HTTP 缓存指令。尤其是因为 OP 提到了 PWA,所以 Service Worker 在这里是一个更好的解决方案,因为它们是为这个确切的问题而设计的。
  • @Phil 如果您想通过一些简单的软件设置指针来扩展它,这将是一个很好的答案。我们正在处理一个类似的问题,通过 axios 从 CDN 获取设计资源,并希望浏览器像缓存典型图像等一样缓存它们
  • 在url中添加查询参数会起作用吗?
猜你喜欢
  • 2020-03-08
  • 2020-08-26
  • 1970-01-01
  • 1970-01-01
  • 2020-05-21
  • 2017-09-09
  • 2017-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多