로그인
- 이메일과 비밀번호로 로그인한다.
→ 이메일과 비밀번호를 body에 담아서 POST방식으로 요청
postman에서 POST요청하기

React에서 POST 요청하기
- idInput과 pwInput의 값을 받아와서 서버에 보낸다.
→ 응답으로 토큰을 받아온다.
⇒ 로컬 스토리지에 토큰 저장!
const id = useRef();
const pw = useRef();
const handleLogin = () => {
fetch("http://localhost:3000/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: id.current.value,
password: pw.current.value,
}),
})
.then((response) => response.json())
.then((json) => localStorage.setItem("token", json.token));
};
토큰으로 유저 정보 불러오기
- 위에서 로그인 후 받은 토큰을 header에 넣어서 요청하면 다시 로그인 할 필요가 없다.
- 이번에는 토큰으로 유저 정보를 받아와보자.
- 아래 예제에서는 토큰을 header에 넣어서 GET요청을 하면 서버에서 유저의 이메일을 응답받을 수 있다.
postman에서 GET 요청하기

React에서 GET 요청하기
const [userEmail, setUserEmail] = useState();
useEffect(() => {
const token = localStorage.getItem("token");
if (!token) {
alert("사용자가 아닙니다.");
return;
}
fetch("http://localhost:8000/users/me", {
method: "GET",
headers: {
token: token,
},
})
.then((response) => response.json())
.then((json) => setUserEmail(json.email));
}, []);
꿀같은 글 잘 읽고 갑니다~
빠이띵! :)