繁体   English   中英

使用 JavaScript Axios/Fetch。 你能禁用浏览器缓存吗?

[英]Using JavaScript Axios/Fetch. Can you disable browser cache?

我正在尝试为我更新到 React.js 的 freeCodeCamp 项目查询报价 API。 我现在正在尝试使用FetchAxios来查询 API,但它正在浏览器中缓存响应。 我知道在$ajax有一个{ cache: false }会强制浏览器执行新请求。

有什么方法可以用FetchAxios做同样的事情吗?

cache-control设置似乎已经被Axios设置为max-age: 0

在此处输入图片说明

这是我查询 API 的代码。

generateQuote = () => {
  axios.get('https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1')
    .then(response => {
      const { title, content, link } = response.data[0];
      console.log(title, content, link)
      this.setState(() => ({ title, content, link }));
    })
    .catch(err => {
      console.log(`${err} whilst contacting the quote API.`)
    })

}

好的,所以我找到了解决方案。 我必须在 API url 上设置时间戳才能让它进行新调用。 似乎没有办法强制axiosfetch禁用缓存。

这就是我的代码现在的样子

axios.get(`https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&timestamp=${new Date().getTime()}`)
  .then(response => {
    const { title, content, link } = response.data[0];
    console.log(title, content, link)
    this.setState(() => ({ title, content, link }));
  })
  .catch(err => {
    console.log(`${err} whilst contacting the quote API.`)
  })

我将这些标头添加到所有 axios 请求中,并且运行良好。

axiosInstance.defaults.headers = {
  'Cache-Control': 'no-cache',
  'Pragma': 'no-cache',
  'Expires': '0',
};

我认为您只需要在每次进行 axios 调用时使 url 不同。 时间戳只是这样做的一种方式。 如果您正在开发 PWA,还可以考虑禁用或过滤 Service Worker 缓存方法。

看来,添加时间戳是唯一始终有效的方法。

如果您使用的是 Vue,例如:

const api = axios.create({
  baseURL: 'https://example.com/api',
  params: {
    t: new Date().getTime()
  }
})
Vue.prototype.$api = api

因此,您可以将其用于:

this.$api.get('items')

并且它总是会根据当前请求时间向 url 添加不同的时间戳。

创建一个 axios 实例,然后为每个请求添加时间戳。

const axiosInstance = axios.create({})

axiosInstance.interceptors.request.use(
    function (config) {
      // Do something before request is sent
      config.params = { ...config.params, timestamp: Date.now() };
      return config;
    },
    function (error) {
      // Do something with request error
      return Promise.reject(error);
    }
  );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM