cookie with Axios

Seungrok Yoon (Lethe)·2023년 8월 26일
1

[TIL] 성장 한 스푼

목록 보기
30/49

https://www.w3schools.com/js/js_cookies.asp

쿠키는 새로운 쿠키를 추가한다고 해서 이전 쿠키가 지워지는 것이 아니고 쌓인다.

https://github.com/axios/axios#global-axios-defaults

export interface AxiosResponse<T = any, D = any> {
  data: T;
  status: number;
  statusText: string;
  headers: RawAxiosResponseHeaders | AxiosResponseHeaders;
  config: InternalAxiosRequestConfig<D>;
  request?: any;
}

const BASE_API_URL = 'https://www.pre-onboarding-selection-task.shop'
const TOKEN_KEY_STR = 'access_token'
const withBearer = (tokenStr: string) => `Bearer ${tokenStr}`

export const axiosInstance = axios.create({
  baseURL: BASE_API_URL,
  headers: {
    'Content-Type': 'application/json',
  },
})

axios.interceptors.request.use(function (config) {
  const token = localStorage.getItem(TOKEN_KEY_STR)
  if (token !== null) config.headers.Authorization = withBearer(token)
  return config
})

export const api = {
  get: <T>(url: string, config?: AxiosRequestConfig) =>
    axiosInstance.get<T>(url, config),
  post: <T, D>(url: string, data: D, config?: AxiosRequestConfig) =>
    axiosInstance.post<T>(url, data, config),
}

axiosInstance.get, post 등등은 AxiosResponse객체를 리턴한다.

AxiosReponse는 <T,D>타입의 제네릭을 받을 수 있는데, T는 AxiosResponse.data의 타입이다.

서버에서 우리에게 주는 특정 데이터들은 AxiosResponse.data에 담겨서 온다.

axiosInstance.post는 3개의 제네릭 타입을 받는다. 첫 번째는 T=> AxiosResponse.data의 타입이다.

그래서 axiosInstance.post<T> 를 하면 AxiosReponse<T,any>타입의 결과를 리턴하게 된다.

아하...그렇군.

HTTP Status Code

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

profile
안녕하세요 개발자 윤승록입니다. 내 성장을 가시적으로 기록하기 위해 블로그를 운영중입니다.

0개의 댓글