๐จFrontEnd/React
๋ฆฌ์กํธ axios instance & interceptor/ axios ์๋ฌ ํธ๋ค๋ง
IOTrue
2023. 2. 5. 19:53
๐ ๋ฆฌ์กํธ axios instance & interceptor/ axios ์๋ฌ ํธ๋ค๋ง
์ด๋ฒ ํ๋ก์ ํธ ์ฝ๋๋ฅผ ์์๋ก ์ฌ์ฉํ๊ฒ ๋ค
โ axios instance (์ธ์คํด์ค)
axios instance๋
axios๋ฅผ ์ฌ์ฉํ ๋ ๊ณตํต์ผ๋ก ๋ค์ด๊ฐ๋ ๊ธฐ๋ณธ ์ฝ๋๋ฅผ ๋ชจ๋ํ ํ ์ ์๋ ๋ฐฉ๋ฒ์ด๋ค.
import axios from "axios";
export const api = axios.create({
baseURL: "๊ธฐ๋ณธ์ผ๋ก ์ง์ ํ ์๋ฒ url",
timeout: 1000, //์์ฒญ์ด ํด๋น ์ค์ ์๊ฐ๋ณด๋ค ์ง์ฐ๋ ๊ฒฝ์ฐ ์์ฒญ์ ์ค๋จ๋๋ฉฐ, catch๋ก ์๋ฌ๊ฐ ์ ๋ฌ๋๋ค
headers: {
"content-type": "application/json;charset=UTF-8",
//"Accept": "application/json," ์ฃผ์ ์ด์ : ๊ธฐ๋ณธ ๊ฐ์ด application/json ์ด๋ค.
},
});
โ axios interceptor (์ธํฐ์ ํฐ)
axios interceptor๋
axios๋ฅผ ์ฌ์ฉํ ๋ API ์์ฒญ๊ณผ ์๋ต์ ๋ํ ์๋ฌ ํธ๋ค๋ง ๋ฐ ๊ณตํต ์์ ์ ๋ชจ๋ํ ํ ๋ ์ฌ์ฉํ๋ค.
api.interceptors.request.use( //์์ฒญ ์ฒ๋ฆฌ
function (config) {
const token = localStorage.getItem("token");
const refreshToken = localStorage.getItem("refreshToken");
try {
if (token && refreshToken) { //ํ ํฐ์ด ์๋ค๋ฉด headers์ ํ ํฐ ์ถ๊ฐ
config.headers.authorization = token;
config.headers.refreshauthorization = refreshToken;
}
return config;
} catch (error) {
alert("์๋ฒ ์์ฒญ ์๋ฌ! ๋ค์ ์๋ํด์ฃผ์ธ์!");
}
return config;
},
function (error) {
return Promise.reject(error);
}
);
api.interceptors.response.use( //์๋ต ์ฒ๋ฆฌ
function (response) {
return response;
},
function (error) {
alert("์๋ฒ ์๋ต ์๋ฌ! ๋ค์ ์๋ํด์ฃผ์ธ์!");
return Promise.reject(error);
}
);
โ axios instance, interceptor ์ ์ฉ
import { api } from "../../shared/api";
export const __loginUser = createAsyncThunk(
"loginUser",
async (payload, thunkAPI) => {
try {
//์๋ api.post ๋ถ๋ถ์ด instance๋ฅผ ์ฌ์ฉํ ๋ถ๋ถ์ด๋ค
const data = await api.post(`auth/local`, payload);
//๊ณตํต ์์ฒญ,์๋ต ์ฒ๋ฆฌ๊ฐ ์๋ ๊ฐ๋ณ ์ฒ๋ฆฌ๋ ๋ฐ๋ก ํด์ค์ผ ํ๋ค
if (data.status === 201) { //๋ก๊ทธ์ธ ์์
๊ฐ๋ณ ์ฒ๋ฆฌ
const accessToken = data.data.token.AccessToken;
const refreshToken = data.data.token.RefreshToken;
const nickName = data.data.nickname;
if(accessToken && refreshToken && nickName){ //ํ ํฐ & ๋๋ค์์ด ์๋ค๋ฉด
localStorage.setItem("token", accessToken);
localStorage.setItem("refreshToken", refreshToken);
localStorage.setItem("nickName", nickName);
alert("๋ก๊ทธ์ธ ์ฑ๊ณต!!!");
return window.location.assign("/main");
}
}
return thunkAPI.fulfillWithValue(data);
} catch (error) {
alert("๋ค์ ํ์ธํด์ฃผ์ธ์.");
return thunkAPI.rejectWithValue(error);
}
}
);
์ฐธ๊ณ
์ธ์คํด์ค : https://axios-http.com/kr/docs/instance
์ธํฐ์ ํฐ : https://axios-http.com/kr/docs/interceptors