![article thumbnail image](https://blog.kakaocdn.net/dn/vp6yi/btrGb66doZf/G5RpymMK53QZFQHhhLhP8k/img.png)
728x90
Object is possibly undefined
❓상황
axios에서 interceptors로 headers에 Authorization 값을 부여할때, 빨간 줄이 나오는 문제
🔎 원인 파악
config.headers는 axios request headers를 가질 수도 있고, undefined도 가질 수 있다.
(property) AxiosRequestConfig<any>.headers?: AxiosRequestHeaders | undefined
값이 undefined인 경우일때, 접근 한 경우 에러가 발생한다.
How to fix config.headers.Authorization "Object is possibly undefined" when using axios interceptors
I got the following code : loggedInAxios.interceptors.request.use( async (config) => { if (isTokenExpired('access_token')) { const response = await getRefreshToken(); await
stackoverflow.com
✨ 해결 방법
1. config.headers의 값이 있는 경우에만 작동하도록 하기
config.headers?.Authorization = `Bearer ${accessToken}`;
2. config.headers의 값이 undefined일 경우 빈 객체를 넣어 값 할당해주기
if(!config.headers) config.headers = {};
3. 처음부터 config.headers property를 재 설정해주기. : 내가 채택한 해결 방법
config.headers = {
Authorization: `Bearer ${accessToken}`,
};
'공부 > 오류' 카테고리의 다른 글
오류 | Link 태그에 a태그 대신, 컴포넌트 입력시 발생하는 오류(feat. Next.js) (0) | 2022.07.06 |
---|---|
공부 | Git Hub 다른 사람 원격저장소 git pull (0) | 2022.07.05 |
오류 | map 함수 2 (feat. React) (0) | 2022.06.27 |
오류 | map 함수 1 (ft. react) (0) | 2022.06.26 |
오류 | parsing Error(feat. React) (0) | 2022.06.26 |