From 1f4157dc625871e89ff1d18c561818c5a687a74d Mon Sep 17 00:00:00 2001 From: witch-factory Date: Sun, 8 Sep 2024 22:10:32 +0900 Subject: [PATCH] =?UTF-8?q?jwt=20=EB=A1=9C=EA=B7=B8=EC=9D=B8=20=EC=84=B8?= =?UTF-8?q?=ED=8C=85=20=EC=A4=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../project-jwt-login-with-nextjs-1/index.md | 92 ++++++++++++++++++- 1 file changed, 88 insertions(+), 4 deletions(-) diff --git a/content/project-jwt-login-with-nextjs-1/index.md b/content/project-jwt-login-with-nextjs-1/index.md index ef984199..9f551677 100644 --- a/content/project-jwt-login-with-nextjs-1/index.md +++ b/content/project-jwt-login-with-nextjs-1/index.md @@ -1,13 +1,13 @@ --- title: JWT 로그인 구현하기 - 첫번째, 준비하기 -date: "2024-08-21T00:00:00Z" +date: "2024-09-03T00:00:00Z" description: "로그인 구현을 위해 프로젝트를 준비하고 기본적인 설정을 하자" tags: ["typescript", "javascript", "web"] --- # 이 글은 작성 중입니다. -이번에는 프로젝트에 JWT를 이용한 로그인을 달아 보기로 했다. 그러면서 간단히 데모를 구현해 본 흔적을 여기 남긴다. +이번에 프로젝트에 JWT를 이용한 로그인을 달아 보기로 했다. 그러면서 간단히 데모를 구현해 본 흔적을 여기 남긴다. 실제 프로젝트에 똑같이 적용할 것이므로 Node, Express, Prisma를 이용하여 서버를 구현하고 간단한 로그인 기능이 있는 React 프로젝트와 연동할 것이다. @@ -199,9 +199,9 @@ export default authRouter; app.use("/auth", authRouter); ``` -# 4. 간단한 테스트 페이지 구현 +# 4. 간단한 클라이언트 구현 -데모에서 사용할 페이지를 만들어보자. react를 이용할 것이다. +데모에서 사용할 로그인, 회원가입 페이지를 만들어보자. react를 이용한다. 먼저 프론트엔드 프로젝트를 생성한다. vite의 react + typescript 템플릿을 이용한다. @@ -215,6 +215,90 @@ npm create vite@latest client -- --template react-ts npm install react-router-dom ky ``` +그리고 ky 인스턴스를 정의한다. 서버 도메인을 추가하고 서로 다른 도메인에서 요청을 보낼 것이므로 `credentials: "include"` 옵션을 추가한다. + +```typescript +// utils/apiClient.ts +import ky from "ky"; + +const apiClient = ky.create({ + prefixUrl: "http://localhost:3000", + credentials: "include", + throwHttpErrors: false, +}); + +export default apiClient; +``` + +## 4.1. 로그인 페이지 + +로그인 페이지는 다음과 같이 정의한다. 스타일은 거의 신경쓰지 않았고 아직 기능은 구현하지 않았으므로 `handleSubmit` 함수도 서버로 단순히 요청을 보내기만 한다. + +```tsx +import { useState } from "react"; +import apiClient from "./utils/apiClient"; + +type LoginCredentials = { + username: string; + password: string; +}; + +function LoginPage() { + const [credentials, setCredentials] = useState({ + username: "", + password: "", + }); + + const handleChange = (e: React.ChangeEvent) => { + const { name, value } = e.target; + setCredentials((prev) => ({ + ...prev, + [name]: value, + })); + }; + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + console.log(credentials); + apiClient.post("/auth/login", { json: credentials }); + }; + + return ( + <> +

로그인

+
+ + + +
+ 회원가입 + + ); +} + +export default LoginPage; +``` + +## 4.2. 회원가입 페이지 + +회원가입 페이지도 다음과 같이 간단히만 구현하였다. + +계속... + # 참고