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

时间:2018-03-13 18:39:08

标签: javascript reactjs fetch axios

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

我可以通过某种方式对FetchAxios执行相同操作吗?

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

enter image description here

这是我查询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.`)
    })

}

5 个答案:

答案 0 :(得分:13)

好的,我找到了解决方案。我必须在API网址上设置时间戳才能让它进行新的通话。似乎没有办法强制import { ADD_TODO } from './actions' function todos(state = {}, action) { switch(action.type) { case ADD_TODO: return [ ...state, { text: action.text } ] default: return state } } export default todos axios禁用缓存。

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

fetch

答案 1 :(得分:4)

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

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

答案 2 :(得分:0)

我认为您每次拨打axios调用时都只需要使URL不同即可。时间戳只是其中一种方法。如果要开发PWA,还请考虑禁用或过滤服务人员缓存方法。

答案 3 :(得分:0)

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

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

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

所以你可以使用它:

this.$api.get('items')

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

答案 4 :(得分:-1)

创建一个 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);
    }
  );