[axios] 응답 Header로 Token 전달받기

moontag·2022년 9월 26일
1

프로젝트

목록 보기
4/6

FE단에서 서버가 보낸 응답 헤더에서 토큰을 전달받기


잘못된 방식 ❌

  1. 응답 헤더에서 Authorization으로 온 토큰을 받고
  2. LocalStorage에 저장하기
  • res.headers.Authorization => 잘못된 방식
  • console에 찍어보면 undefined가 출력됐었음
    axios.defaults.withCredentials = true; // withCredentials 전역 설정
    axios
      .post(`${URL}/login`, data)
      .then((res) => {
        if (res.status === 200) {
          let accessToken = res.headers.Authorization; // 응답헤더에서 토큰 받기
          let refreshToken = res.headers.refresh; // 응답헤더에서 토큰 받기
          console.log('refresh 토큰 :', refreshToken);
          console.log('access 토큰 :', accessToken);
          setLocalStorage('access_token', accessToken); // 토큰 localStorage에 저장
          axios.defaults.headers.common[
            'Authorization'
          ] = `Bearer ${accessToken}`;
          navigate('/');
        }
      })
      .catch((error) => console.log(error));





axios 응답 헤더로 받는 방식 ✅

  • 모든 헤더이름은 소문자이고 대괄호 표기법을 사용하여 접근 가능
    예) response.headers['content-type']
    axios 공식문서

Header로 authorization토큰 받는 방법

  1. [''] 대괄호표기법
let accessToken = res.headers['authorization']; 
let refreshToken = res.headers['refresh'];
  1. . key값으로 가져오기
    • 여기서 headers 이름들은 소문자!!!! 대문자쓰면 안됨!!!!!! 명심!!!
      ex) res.headers.authorization
let accessToken = res.headers.authorization; // 응답헤더에서 토큰 받기
  let refreshToken = res.headers.refresh; // 응답헤더에서 

예시

    axios.defaults.withCredentials = true; // withCredentials 전역 설정
    axios
      .post(`${URL}/login`, data)
      .then((res) => {
        if (res.status === 200) {
          // 모든 헤더 이름은 소문자
          let accessToken = res.headers['authorization']; // 응답헤더에서 토큰 받기
          let refreshToken = res.headers['refresh']; // 응답헤더에서 토큰 받기
          console.log('access 토큰 :', accessToken);
          console.log('refresh 토큰 :', refreshToken);
          setLocalStorage('access_token', accessToken); // 토큰 localStorage에 저장
          axios.defaults.headers.common[
            'Authorization'
          ] = `Bearer ${accessToken}`;
          navigate('/');
        }
      })






소문자였다니,, 잘 알고 삽질하지 말자,,

참고

https://kingchan223.tistory.com/230
axios 공식문서

profile
터벅터벅 나의 개발 일상

0개의 댓글