What I Learned/SpartaCodingClub
[내일배움캠프] 2023-01-02 TIL
Interrobang
2023. 1. 2. 18:13
JWT 토큰 프론트에서 활용
문제점
로그인시 JWT토큰을 생성하고 미들웨어에 활용하는 법을 익혔으나, 프론트와 백엔드를 연결할 때 이를 이용하지 못함
시도해본 것들
쿠키를 이용해서 해보기?, 새로운 미들웨어를 만들어보기, ...
해결
프론트의 script 부분에서 localstorage를 이용하여 로그인, 로그아웃을 구현하고, header 값을 주어 미들웨어를 사용할 수 있게 함
로그인
if (localStorage.getItem("token")) {
getSelf(function () {
alert("이미 로그인이 되어있습니다.");
window.location.replace("/");
});
}
function sign_in() {
let nickname = $("#nickname").val();
let password = $("#inputPassword").val();
$.ajax({
type: "POST",
url: "/api/login",
data: {
nickname: nickname,
password: password,
},
success: function (response) {
localStorage.setItem("token", response.token);
window.location.replace("/");
},
error: function (error) {
customAlert(error.responseJSON.errorMessage);
},
});
}
로그아웃
function signOut() {
localStorage.clear();
window.location.href = "/";
}
HTTP Method 이용시
$.ajax({
type: "...",
url: `...`,
headers: {
authorization: `Bearer ${localStorage.getItem("token")}`,
},
...
알게 된 점
백엔드만 활용한 공부를 하다보니 이런 부분에서 모르는 것이 많았다. 프론트에서 어떻게 사용할 건지에 대한 이해도 충분히 필요함을 느꼈다.