重新启动笔记本电脑后工作了大约 2 个月后,代码停止工作。它应该作为拦截器工作,我不确定它为什么停止

问题描述 投票:0回答:1

重新启动计算机后,我用于拦截器的代码停止工作(我相信这就是我的项目停止工作的原因)

import axios from "axios";

let refresh = false;

axios.interceptors.response.use(
  (resp) => resp,
  async (error) => {
    if (error.response.status === 401 && !refresh) {
      refresh = true;
      console.log(localStorage.getItem('refresh_token'));

      const response = await axios.post(
        'http://localhost:8000/token/refresh/',
        {
          refresh: localStorage.getItem('refresh_token'),
        },
        {
          headers: 'Content-Type: application/json',
        },
        { withCredentials: true }
      );

      if (response.status === 200) {
        axios.defaults.headers.common['Authorization'] = `Bearer ${response.data['access']}`;
        localStorage.setItem('access_token', response.data.access);
        localStorage.setItem('refresh_token', response.data.refresh);
        return axios(error.config);
      }
    }

    refresh = false;
    return error;
  }
);

我尝试做到这一点,因此如果错误未定义,它会重新尝试执行代码

reactjs axios interceptor
1个回答
0
投票

import axios from "axios";

let refresh = false;

axios.interceptors.response.use(
  (resp) => resp,
  async (error) => {
    if (error.response && error.response.status === 401 && !refresh) {
      refresh = true;

      try {
        const response = await axios.post(
          'http://localhost:8000/token/refresh/',
          { refresh: localStorage.getItem('refresh_token') },
          { headers: { 'Content-Type': 'application/json' }, withCredentials: true }
        );

        if (response.status === 200) {
          axios.defaults.headers.common['Authorization'] = `Bearer ${response.data['access']}`;
          localStorage.setItem('access_token', response.data.access);
          localStorage.setItem('refresh_token', response.data.refresh);
          refresh = false;
          return axios(error.config);
        }
      } catch (refreshError) {
        console.error('Error refreshing token:', refreshError);
      }
    }

    refresh = false;
    return Promise.reject(error);
  }
);

如果有效请告诉我!

© www.soinside.com 2019 - 2024. All rights reserved.