0

I'm encountering an issue where my API responses are not updating unless I disable cache in the browser's DevTools. Here are the details:

Problem: When I make API calls using axios in my React application, the responses seem to be cached, and I do not receive the latest data. The only way to get the updated response is to disable the cache in the DevTools.

Current Implementation: Here is the helper function I'm using to send requests:

import { openNotificationWarning } from '@/components/Notification';
import { getAuthority, removeAuthority } from '@/utils/authority';
import axios from 'axios';
import { formatMessage } from 'umi';

axios.defaults.baseURL = process.env.API_URL;

function getCookie(value) {
  const reg = new RegExp(`(^| )${value}=([^;]*)(;|$)`);
  const arr = document.cookie.match(reg);
  try {
    if (arr) {
      return unescape(arr[2]);
    }
  } catch (error) {
    return null;
  }
  return null;
}
const instance = axios.create({
  baseURL: process.env.API_URL,
  timeout: 600000,
  withCredentials: false,
});
instance.interceptors.request //REQUEST
  .use(
    async function (config) {
      let authority = getAuthority();
      var headers = { ...config.headers };
      if (authority) {
        headers['Authorization'] = `Bearer ${authority}`;
      }
      headers['X-Requested-With'] = 'XMLHttpRequest';
      headers['Content-Type'] = 'application/json';
      headers['X-XSRF-TOKEN'] = getCookie('XSRF-TOKEN');
      config.headers = headers;
      return config;
    },
    (error) => {
      if (error && error.request) {
      }
      return Promise.reject(error);
    },
  );
instance.interceptors.response.use(
  async function (response) {
    if (response.status === 401) {
      removeAuthority();
    }
    return {
      response,
      data: response.data,
    };
  },
  (error) => {
    if (error?.response?.status == 401) {
      removeAuthority();
    }

    if (error?.response?.status == 403) {
      openNotificationWarning(
        'このサイトへアクセスは許可されていません。',
        formatMessage({ id: 'pleaseCheckAgain' }),
        '#f81d22',
      );
    }
    if (error?.response?.data?.message == 'User is not logged in.') {
      removeAuthority();
    }
    if (
      error?.response?.data?.message ==
      `Cannot read properties of undefined (reading 'access_token')`
    ) {
      removeAuthority();
    }
    return { response: error, error: error.response };
  },
);

const request = (url, options) => {
  return instance.request({ ...options, url: url });
};

export default request;

Things I've Tried:

Disabling cache in browser DevTools (works, but not a practical solution for production).

I would appreciate any guidance on how to ensure that my API responses are not cached and always return the latest data.

Thanks a lot for your time and help!

7
  • None of the code in this question is relevant. Response caching can be controlled via appropriate response headers set by the server. You might be able to avoid caching by adding a dynamic parameter but that's not always guaranteed to work Commented Nov 29, 2024 at 4:40
  • 1
    Duplicate: Using JavaScript Axios/Fetch. Can you disable browser cache? Commented Nov 29, 2024 at 4:40
  • This is my API reponse header: HTTP/1.1 200 OK Server: nginx Content-Type: application/json Transfer-Encoding: chunked Connection: keep-alive Vary: Accept-Encoding Cache-Control: no-cache, private Date: Fri, 29 Nov 2024 04:41:09 GMT X-RateLimit-Limit: 60 X-RateLimit-Remaining: 56 Access-Control-Allow-Origin: * X-Frame-Options: SAMEORIGIN X-XSS-Protection: 1; mode=block X-Content-Type-Options: nosniff Content-Encoding: gzip Commented Nov 29, 2024 at 4:43
  • 1
    Cache-Control: no-cache doesn't do what you think it does ~ developer.mozilla.org/en-US/docs/Web/HTTP/Headers/… Commented Nov 29, 2024 at 4:47
  • Thank you for the very useful information. Commented Nov 29, 2024 at 5:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.