Skip to content

Commit

Permalink
jwt 로그인 세팅 중
Browse files Browse the repository at this point in the history
  • Loading branch information
witch-factory committed Sep 8, 2024
1 parent 6bb8c51 commit 1f4157d
Showing 1 changed file with 88 additions and 4 deletions.
92 changes: 88 additions & 4 deletions content/project-jwt-login-with-nextjs-1/index.md
Original file line number Diff line number Diff line change
@@ -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 프로젝트와 연동할 것이다.

Expand Down Expand Up @@ -199,9 +199,9 @@ export default authRouter;
app.use("/auth", authRouter);
```

# 4. 간단한 테스트 페이지 구현
# 4. 간단한 클라이언트 구현

데모에서 사용할 페이지를 만들어보자. react를 이용할 것이다.
데모에서 사용할 로그인, 회원가입 페이지를 만들어보자. react를 이용한다.

먼저 프론트엔드 프로젝트를 생성한다. vite의 react + typescript 템플릿을 이용한다.

Expand All @@ -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<LoginCredentials>({
username: "",
password: "",
});

const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;
setCredentials((prev) => ({
...prev,
[name]: value,
}));
};

const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
console.log(credentials);
apiClient.post("/auth/login", { json: credentials });
};

return (
<>
<h2>로그인</h2>
<form onSubmit={handleSubmit}>
<input
type='text'
name='username'
placeholder='사용자명'
required
value={credentials.username}
onChange={handleChange}
/>
<input
type='password'
name='password'
placeholder='비밀번호'
required
value={credentials.password}
onChange={handleChange}
/>
<button type='submit'>로그인</button>
</form>
<a href='/register'>회원가입</a>
</>
);
}

export default LoginPage;
```

## 4.2. 회원가입 페이지

회원가입 페이지도 다음과 같이 간단히만 구현하였다.

계속...


# 참고

Expand Down

0 comments on commit 1f4157d

Please sign in to comment.