简体   繁体   English

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

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

I am trying to query a quote API for a freeCodeCamp project I'm updating to React.js.我正在尝试为我更新到 React.js 的 freeCodeCamp 项目查询报价 API。 I am now trying to use Fetch or Axios to query the API but it's caching the response in the browser.我现在正在尝试使用FetchAxios来查询 API,但它正在浏览器中缓存响应。 I know in $ajax there is a { cache: false } that would force the browser to do a new request.我知道在$ajax有一个{ cache: false }会强制浏览器执行新请求。

Is there some way I will be able to do the same with Fetch or Axios ?有什么方法可以用FetchAxios做同样的事情吗?

The cache-control setting seems to be already set to max-age: 0 by Axios . cache-control设置似乎已经被Axios设置为max-age: 0

在此处输入图片说明

This is my code I have that is querying the API.这是我查询 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.`)
    })

} }

Okay so I found a solution.好的,所以我找到了解决方案。 I had to set a timestamp on the API url to get it to make a new call.我必须在 API url 上设置时间戳才能让它进行新调用。 There doesn't seem to be a way to force axios or fetch to disable cache.似乎没有办法强制axiosfetch禁用缓存。

This is how my code now looks这就是我的代码现在的样子

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.`)
  })

I added these headers to all axios requests and it's working well.我将这些标头添加到所有 axios 请求中,并且运行良好。

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

I think you just need to make the url different each time you make the axios call.我认为您只需要在每次进行 axios 调用时使 url 不同。 Timestamp is just one way to do so.时间戳只是这样做的一种方式。 Also consider disabling or filtering service workers caching method if you are developing a PWA.如果您正在开发 PWA,还可以考虑禁用或过滤 Service Worker 缓存方法。

It seems, adding timestamp is the only always working way.看来,添加时间戳是唯一始终有效的方法。

If you're using Vue, for example:如果您使用的是 Vue,例如:

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

So you can use it with:因此,您可以将其用于:

this.$api.get('items')

And it will always add different timestamp to the url, depending on current request time.并且它总是会根据当前请求时间向 url 添加不同的时间戳。

Create an instance of axios and then add timestamp to every request.创建一个 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