나의 블로그
[React + Node.js] VS Code로 로그인 기능 구현하기 본문
- propass라는 폴더 안에 frontend와 backend 폴더를 나누어 각각 프론트엔드와 백엔드 작업을 한다
- 실행 시에는 VS Code의 터미널을 두 개 열어 각각 React와 백엔드 서버를 실행 시킨다
1. 프로젝트 폴더 구조
propass/ # 프로젝트 최상위 폴더
├── backend/ # 백엔드 관련 파일들
│ ├── index.js # 백엔드 서버 코드
│ └── package.json # 백엔드 종속성 및 설정
└── frontend/ # 프론트엔드 관련 파일들
├── package.json # 프론트엔드 종속성 및 설정
├── src/ # 프론트엔드 소스 코드
└── public/ # 정적 파일
2. 프론트엔드 설정 (React)
1. 프론트엔드 폴더에서 React 프로젝트 생성
- . : 현재 폴더에 React 앱을 생성
cd propass/frontend
npx create-react-app .
2. React 앱 실행
- React 앱은 기본적으로 localhost:3000에서 실행된다
npm start
3. React에서 백엔드 요청 보내기
- fetch나 axios를 사용하여 백엔드 API 요청을 보낸다
- 예 : React에서 로그인 API 요청 보내기
const handleLogin = async () => {
const response = await fetch("<http://localhost:5000/login>", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
});
const data = await response.json();
if (data.success) {
alert("로그인 성공!");
} else {
alert("로그인 실패: " + data.message);
}
};
3. 백엔드 설정 (Node.js + Express)
1. 백엔드 폴더에서 Node.js 프로젝트 설정
- backend 폴더에서 npm init -y로 package.json을 생성한 후 필요한 패키지들을 설치한다
cd propass/backend
npm init -y
npm install express body-parser cors
2. 백엔드 서버 코드 작성 (index.js)
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
app.use(cors()); // CORS 허용
app.use(bodyParser.json()); // JSON 파싱
const users = [{ email: "test@example.com", password: "1234" }];
app.post("/login", (req, res) => {
const { email, password } = req.body;
const user = users.find((u) => u.email === email && u.password === password);
if (user) {
res.json({ success: true, message: "로그인 성공!" });
} else {
res.json({ success: false, message: "이메일 또는 비밀번호가 잘못되었습니다." });
}
});
app.listen(5000, () => {
console.log("서버가 5000번 포트에서 실행 중...");
});
3. 백엔드 서버 실행
- 백엔드 서버는 기본적으로 localhost:5000에서 실행된다.
node index.js
4. 동작 방식 및 결과
- 프론트엔드 : React 앱이 npm start로 localhost:3000에서 실행됨
- 백엔드 : Express 서버가 node index.js로 localhost:5000에서 실행됨
- React 앱에서 백엔드로 요청을 보내면, 백엔드가 해당 요청을 처리하고 응답을 React 앱에 전달함
추가 고려사항
- 데이터베이스 연동: MongoDB, MySQL 등과 연결해 사용자 데이터를 저장한다.
- JWT 토큰: 인증 상태를 유지하려면 JWT(JSON Web Token) 기반의 인증 시스템을 추가로 구현한다.
'VS Code' 카테고리의 다른 글
| [Node.js] npm install express body-parser cors (1) | 2024.11.24 |
|---|---|
| [React + Node.js] 모듈화 작업 (0) | 2024.11.24 |