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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49263559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:20:36  来源:igfitidea点击:

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

javascriptreactjsfetchaxios

提问by Asjas

I am trying to query a quote API for a freeCodeCamp project I'm updating to React.js. I am now trying to use Fetchor Axiosto query the API but it's caching the response in the browser. I know in $ajaxthere is a { cache: false }that would force the browser to do a new request.

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

Is there some way I will be able to do the same with Fetchor Axios?

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

The cache-controlsetting seems to be already set to max-age: 0by Axios.

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

enter image description here

在此处输入图片说明

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

}

}

回答by Asjas

Okay so I found a solution. I had to set a timestamp on the API url to get it to make a new call. There doesn't seem to be a way to force axiosor fetchto disable cache.

好的,所以我找到了解决方案。我必须在 API url 上设置时间戳才能让它进行新调用。似乎没有办法强制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.`)
  })

回答by Al Herrera

I think you just need to make the url different each time you make the axios call. Timestamp is just one way to do so. Also consider disabling or filtering service workers caching method if you are developing a PWA.

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