N
N
Nikita Andreevich2020-07-17 11:07:25
React Native
Nikita Andreevich, 2020-07-17 11:07:25

How to implement axios.interseptors to save and update token?

Hello. Please tell me how to implement interseptor in axios to save the default token and update?
Below is the code I currently have and it doesn't work. I still end up with a 401 error in the console.

var APIKit = axios.create({ baseURL: url });
;

export const setClientRefreshToken = async () => {
  let refTokenStorage = await AsyncStorage.getItem("refToken");

  let payload = {
    refreshToken: refTokenStorage,
  };

  APIKit.interceptors.response.use(
    (response) => {
      return response;
    },
    (error) => {
      const originalRequest = error.config;

      if (error.response.status === 401 && originalRequest.url) {
        //переход на логин скрин
        return Promise.reject(error);
      }
      if (error.response.status === 401 && !originalRequest._retry) {
        originalRequest._retry = true;
        return APIKit.post("/authentication/refresh", payload).then((res) => {
          if (res.status === 201) {
            APIKit.defaults.headers.common["Authorization"] =
              "Bearer " + localStorageService.getAccessToken();
            //переход на скрин где был баг
            return APIKit(originalRequest);
          }
        });
      }
    }
  );
};

export const setClientToken = async () => {
  let token = await AsyncStorage.getItem("token");

  APIKit.interceptors.request.use(
    (config) => {
      if (token) {
        config.headers["Authorization"] = `Bearer ${token}`;
      }
      return config;
    },
    (error) => {
      Promise.reject(error);
    }
  );
};

export default APIKit;


I also tried using the axios-auth-refresh lib. Also unsuccessfully (code below)
var APIKit = axios.create({ baseURL: url });

const refreshAuthLogic = async (failedRequest) => {
  let refTokenStorage = await AsyncStorage.getItem("refToken");

  let payload = {
    refreshToken: refTokenStorage,
  };

  APIKit.post("/authentication/refresh", payload).then((rt) => {
    setClientToken(rt.data.token);
    return Promise.resolve();
  });
};

createAuthRefreshInterceptor(APIKit, refreshAuthLogic)

export const setClientToken = async (token) => {
  // let token = await AsyncStorage.getItem("token");

  APIKit.interceptors.request.use(
    (config) => {
      if (token) {
        config.headers["Authorization"] = `Bearer ${token}`;
      }
      return config;
    },
    (error) => {
      Promise.reject(error);
    }
  );
};

export default APIKit;

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question