여러 자료들을 보았지만, 서버에서 token을 받는 과정과 이를 어떻게 저장할 지에 대한 설명이 연계되는 내용이 잘 없어서 어려웠다. 그래서 내 방식대로 진행한 내용을 정리해 보았다.
우선 모듈 부분에
const initialState = {
memberList: [
{
memberId: "",
nickname: "",
password: "",
},
],
isLoading: false,
error: null,
isLogin: false,
};
로그인할 맴버의 초기정보 값을 정한다 .
이때 isLogin으로 유저가 로그인 되었는지 판별하려 했다.
로그인 하는 코드는 아래와 같이 구성하였다.
export const __postLogin = createAsyncThunk(
"POST_LOGIN",
async (payload, thunkAPI) => {
try {
// console.log(payload);
const { data } = await http
.post("/members/login", payload)
.then((res) => {
sessionStorage.setItem("accessToken", res.headers.accessToken);
sessionStorage.setItem("refreshToken", res.headers.refreshToken);
return res;
});
console.log(data); // 성공하면 토큰이 찍힘
return thunkAPI.fulfillWithValue(data);
} catch (error) {
return thunkAPI.rejectWithValue(error);
}
}
);
이때 axios 인스턴스인 http를 사용했다.
// ./api/http.js
import axios from "axios";
const http = axios.create({
baseURL: "http://3.38.99.102:3010",
timeout: 10000,
});
로그인에 성공하면 토큰을 받는데 토큰은 아래와 같다

이때 로그인 전에는 isLogin이 false였지만 후에는 true로 바뀌었다. 이를 활용해서, 컴퍼넌트에서 로그인이 되었을때~ 라는 기능을 구현할 수 있다.
isLogin을 로그인하였을 때 true로 바꾸는 코드는 아래와 같다.
const memberListSlice = createSlice({
name: "memberList",
initialState,
reducers: {},
extraReducers: {
[__postLogin.pending]: (state) => {
state.isLoading = true;
},
[__postLogin.fulfilled]: (state, action) => {
state.isLoading = false;
state.isLogin = true;
sessionStorage.setItem("memberinfo", JSON.stringify(action.payload));
},
[__postLogin.rejected]: (state, action) => {
state.isLoading = false;
state.error = action.payload;
},
},
});
좀 더 이해하고 보완하겠음
참고 자료 :
https://velog.io/@jytrack/React-%EB%A1%9C%EA%B7%B8%EC%9D%B8-%EA%B5%AC%ED%98%84%ED%95%98%EA%B8%B0
봐도 잘 이해가 안되서 영상 보기러 함
[React] 로그인 구현하기
axios를 통해 서버와 통신하여 로그인을 진행하는 로그인 컴포넌트 구현 Redux를 이용해 사용자 정보를 state로 관리 Component, Form, React Hooks, Redux 다루기 기본 구조 App Redux Login Component 
기본적인 axios에 관한 영상인데, Token과 관련된 부분이 없었음.
https://thinkforthink.tistory.com/372
Axios를 이용해서 Access 토큰과 Refresh 토큰을 갱신하는 방법
로그인한 사용자를 식별하기 위해 서버는 클라이언트에게 access 토큰을 발급하고 클라이언트는 인증이 필요한 요청을 할 때마다 header에 access 토큰을 포함시켜서 보낸다. 그런데 보안의 이유로 a
thinkforthink.tistory.com
토큰에 대해서 설명
https://yeri-kim.github.io/posts/jwt-authorization/
jwt으로 로그인 구현하기 - Blog by Yeri
이번 시간에는 access token을 local storage에 저장하고, api 호출 시 request header에 담아 보내는 법을 배우도록 하겠습니다. 지금 로그인 api에서는 로그인이 성공하면 jwt로 만든 access token을 받고 있습니
yeri-kim.github.io
'TIL > 항해산 TIL' 카테고리의 다른 글
| TIL-44일차 axios instance 사용 (0) | 2023.01.17 |
|---|---|
| TIL-43일차 Router useLocation를 이용하기(특정 페이지에만 header 적용) (0) | 2023.01.17 |
| TIL 41일차 modal 에러 해결- 추후 알아봐야 할 듯 (0) | 2023.01.14 |
| TIL - 40일차 Button 컴퍼넌트 만들기 (0) | 2023.01.14 |
| TIL 39일차 리덕스 툴킷 활용 및 코드 피드백. (0) | 2023.01.13 |