Skip to content

Commit

Permalink
✨ feat: axios instance
Browse files Browse the repository at this point in the history
- axios instance를 추가합니다
- 인터셉트를 통해 토큰상태를 미리 확인하고 가져올 수 있습니다
- 인터셉트 로직은 고쳐야합니다

by Hah-nna #14
  • Loading branch information
Hah-nna committed Mar 29, 2024
1 parent 82b727c commit b9e7b6d
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions src/axios/axios.tsx
Original file line number Diff line number Diff line change
@@ -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);
}
);

0 comments on commit b9e7b6d

Please sign in to comment.