SMALL
1. 쿠키 관련 함수 만들기
// src/cookie
import { Cookies } from "react-cookie";
const cookies = new Cookies()
export const setCookie = () => {
return cookies.set()
}
export const getCookie = () => {
return cookies.get()
}
export const removeCookie = () => {
return cookies.remove();
};
- setCookie : 쿠키 저장 ⇒ Login 부분에서 사용
- getCookie : 가져다 쓰기 ⇒ api 부분에서 사용
- removeCookie : 쿠키 삭제 ⇒ button onclick={removeCookie(’쿠키 이름’)} 사용 / 로그아웃
2. 토큰 저장 방법
async 안에 넣기
// src/pages/login.js
const [cookies, setCookie] = useCookies(['userToken']);
export const handleLogin = async () => {
try {
const data = await axios.post('http://13.209.86.39:3003/api/login', state, {
withCredentials: true,
});
const jwtToken = data.data.token; // 받아온 토큰 위치 지정
// jwtToken을 userToken으로 지정 => 쿠키에 토큰 저장
setCookie('jwtToken', jwtToken);
// 여기까지만 하면 쿠키는 잘 받아옴
// user 정보를 localStorage에 저장하는 방법
const decodedUserInformation = jwt_decode(jwtToken); // 토큰 decode
// 토큰에 저장되어있는 userInfo 저장
localStorage.setItem('userInformation ', JSON.stringify(decodedUserInfo));
alert('로그인 성공!');
return data ;
} catch {
alert('문제 있음');
}
};
1) setCookie를 사용해 쿠키를 담는 법
- try에 data를 받아옴
- data에서 토큰이 있는 곳을 지정해 jwtToken으로 만들어줌
- setCookie ⇒ 첫 번째 인자 : 토큰 이름, 두 번째 인자 : 지정한 토큰의 값 (jwtToken)
- 위까지만 해도 쿠키에 토큰의 값이 담김
2) 유저 정보를 localStorage에 저장하는 방법
- npm install jwt-decode
- jwt-decode 라이브러리 다운받고 jwtToken을 decode
- 이를 사용해 userInformation 를 decode해서 저장
- localStorage에 setItem을 사용해 userInformation 를 저장
3. 로그인이 필요한 요청할 때 요청하는 방법
headers 부분에 백엔드에서 원하는 토큰 값을 넣어준다
// src/api/post/postapi.js
export const addComment = async ({ id, newContent }) => {
await axios.post(
`${process.env.REACT_APP_SERVER}/api/posts/${id}/comments`,
newContent,
{
headers: {
authorization: `Bearer ${getCookie('jwtToken')}`,
},
}
);
};
- axios.post의 첫 번째 인자 : URL, 두 번째 인자 : 보내줄 data, 세 번째 인자 : headers
- headers에 우리가 만든 토큰을 백엔드가 원하는 형식으로 넣어줌
- getCookie 안의 값은 우리가 전에 지정한 토큰 이름을 넣어주어야 함 (위와 같은 jwtToken)
4. 유저 정보를 가져오게 하기 위한 과정 (getUser)
export const getUser = () => {
const userInformation =
// loaclStorage에 userInformation을 가져와서 true인지 (값이 있는지)
// 그리고 getCookie()를 통해 쿠키가 있는지?
localStorage.getItem('userInformation ') && getCookie('accessJwtToken')
// 만약 둘이 있다면 localStorage안에 userInformation 를 가져와 userInformation 에 담아줌
? JSON.parse(localStorage.getItem('userInformation ')!)
// 둘 중 하나라도 없으면 null 반환
: null;
return userInformation ;
};
- getUser 함수를 만든다
- localStorage 안에 userInformation 이 존재하고, 쿠키가 존재한다면 userInformation 안에 ‘userInformation ’를 담아줌
- 둘 중 하나라도 없다면 담아주지 않음
5. 로그인 로그아웃 상태 표시
// userInformation이 필요한 파일에
import { getUser }
const userInformation = getUser();
{
userInformation ? (
<button>로그아웃</button>
) : (
<button>로그인</button>
<button>회원가입</button>
)
}
- getUser로 userInformation 가져옴
- userInformation이 존재하는 경우 로그아웃 버튼만 보여줌
- userInformation이 존재하지 않는 경우 로그인, 회원가입 버튼을 보여줌
아직 react cookie에 대해 자세히 알아보지 못하고 프로젝트 마무리를 빨리 해야돼서 자료를 많이 찾아보지 못했다. 확실하게 알고있지 않고 어렴풋이 알고있어 추후에도 react cookie를 사용할 일이 많을 것 같아 정보를 더 많이 찾아보아야 좋을 것 같다.
그리고 react cookie를 사용해 로그인 기능은 완성하였지만, 유저의 정보를 담아 이를 토대로 로그인 혹은 로그아웃이 보이는 기능도 아직 해보지 못했는데, 이 또한 기회가 되면 만들어보고 싶다.
LIST
'Develop_story > TIL(Today I Learned)' 카테고리의 다른 글
React socket.io-client (1) | 2023.03.21 |
---|---|
TypeScript (0) | 2023.03.11 |
RESTful API (0) | 2023.02.28 |
TIL - 68 쿠키, 세션, 쿠키-세션, 토큰 (0) | 2023.02.18 |
TIL - 66 React Query (0) | 2023.02.18 |