From b9e7b6df9ca68acbc7b733ea9e5e3fbba9e65c68 Mon Sep 17 00:00:00 2001 From: Hah-nna Date: Sat, 30 Mar 2024 03:15:21 +0900 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20axios=20instance?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - axios instance를 추가합니다 - 인터셉트를 통해 토큰상태를 미리 확인하고 가져올 수 있습니다 - 인터셉트 로직은 고쳐야합니다 by Hah-nna #14 --- src/axios/axios.tsx | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/axios/axios.tsx diff --git a/src/axios/axios.tsx b/src/axios/axios.tsx new file mode 100644 index 0000000..b6ef8b3 --- /dev/null +++ b/src/axios/axios.tsx @@ -0,0 +1,45 @@ +import axios from "axios"; +// import { getCookie, setCookie } from "../utils/utils"; +import Cookies from "js-cookie"; + +export const instance = axios.create({ + baseURL: import.meta.env.VITE_BASE_URI, +}); + +instance.interceptors.request.use( + async (config) => { + let accessToken: string | null = Cookies.get("accessToken"); + const refreshToken = Cookies.get("refreshToken"); + + if (!accessToken && refreshToken) { + try { + // 리프레시 토큰을 Bearer 토큰 없이 URL 파라미터로 전송 + const response = await axios.post( + `https://today-challenge.site/auth/refresh`, + {}, + { + params: { + refreshToken: refreshToken, + }, + } + ); + + accessToken = response.data.accessToken; + + Cookies.set("accessToken", accessToken); + + // 새로운 엑세스 토큰으로 현재 요청의 헤더 설정 + config.headers["Authorization"] = `Bearer ${accessToken}`; + } catch (error) { + console.error("엑세스 토큰 재발급 실패", error); + } + } else if (accessToken) { + config.headers["Authorization"] = `Bearer ${accessToken}`; + } + + return config; + }, + (error) => { + return Promise.reject(error); + } +);