programing

JavaScript Axios/Fetch 사용.브라우저 캐시를 비활성화할 수 있습니까?

newnotes 2023. 4. 5. 22:13
반응형

JavaScript Axios/Fetch 사용.브라우저 캐시를 비활성화할 수 있습니까?

React.js에 업데이트 중인 freeCodeCamp 프로젝트의 견적 API를 문의하려고 합니다.지금 사용하려고 합니다.Fetch또는AxiosAPI를 쿼리하지만 브라우저에서 응답을 캐싱합니다.나는 알고 있다$ajax이 있다{ cache: false }브라우저가 새 요청을 수행하도록 강제합니다.

제가 같은 일을 할 수 있는 방법이 있을까요?Fetch또는Axios?

cache-control설정이 이미 로 설정되어 있는 것 같습니다.max-age: 0타고Axios.

여기에 이미지 설명 입력

이것은 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에 타임스탬프를 설정하여 새로운 콜을 발신할 수 있도록 해야 했습니다.강제할 방법은 없는 것 같습니다.axios또는fetch캐시를 비활성화합니다.

현재 내 코드는 다음과 같습니다.

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 요구에 대해 캐시를 디세블로 하지 않을 경우 다음 파라미터를 사용하여 1개의 요청에만 캐시를 디세블로 할 수 있습니다.axios호출:

axios.get(
  'https://YOUR-URL.com',
  {
    // query URL without using browser cache
    headers: {
      'Cache-Control': 'no-cache',
      'Pragma': 'no-cache',
      'Expires': '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에 추가됩니다.

엑시오스를 호출할 때마다 URL을 다르게 만들면 된다고 생각합니다.타임스탬프는 그렇게 하는 한 가지 방법일 뿐입니다.또, PWA 를 개발하는 경우는, 서비스 워커의 캐싱 방식을 디세블로 하거나 필터링 하는 것도 고려해 주세요.

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);
    }
  );

언급URL : https://stackoverflow.com/questions/49263559/using-javascript-axios-fetch-can-you-disable-browser-cache

반응형