MySQL, Node Express, React 연결

✒️ 2025-05-28 10:25 내용 수정



환경설정

  1. 프로젝트 폴더를 먼저 생성하고, 하위 폴더로 server 폴더와 client 폴더를 생성한다.
project/
	- server/
	- client/

node and react.png

  1. 프로젝트 폴더에서 npm init으로 서버 설정을 먼저 진행한다.

    • 프로젝트 폴더에 package.json이 생성된다.
  2. 서버에 필요한 라이브러리를 설치한다.

    • express : express.js 사용을 위한 라이브러리
    • cors : CORS 체재 허용 설정을 위한 미들웨어
    • concurrently : 서버와 클라이언트를 동시에 실행하기 위한 script 구문 설정
npm install express cors concurrently
# 글로벌 설정으로 nodemon을 설치하지 않을 경우 명령어가 작동하지 않을 수도 있다.
su npm install --g nodemon
  1. 프로젝트 폴더 하위의 server 폴더에 서버 설정 파일인 server.js 파일을 만든다.
const express = require('express');
const app = express();

const PORT = 10000;

app.listen(PORT, () => {
    console.log(`http://localhost:${PORT}`);
});

app.get("/", (req, res) => {
    res.send("<h1>React server test</h1>");
});
  1. nodemon ./server/server.js로 서버가 실행되는지 확인한다.

node and react 3.png

  1. VSC 터미널에서 프로젝트 폴더 하위의 client 폴더로 cd client를 사용하여 이동한 후, npx create-react-app .으로 React 프로젝트를 설치한다.

    • npx create-react-app . 에서 .은 현재 폴더에 React 프로젝트 설치를 의미한다.
  2. client 폴더에 있는 상태로 npm start를 입력하여 클라이언트가 작동되는지 확인한다.

node and react 4.png

  1. client 폴더에 있는 package.json의 scripts 항목에 proxy 설정을 위해 "proxy" : "서버도메인"을 추가한다.
{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
  // 중략
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
// 중략
  "proxy": "http://localhost/10000"
}
  1. VSC 터미널에서 cd ..를 입력해서 프로젝트 폴더로 이동하고, 프로젝트 폴더의 package.json에서 script 부분에 server와 client 실행 설정, dev 실행 설정을 추가한다.
    • 클라이언트와 서버 실행 시 서로 다른 명령어를 사용했기에 이를 기반으로 설정해준다.
# server(express) 실행 시 사용했던 명령어
node server.js
# 또는
nodemon server.js

# client(react) 실행 시 사용했던 명령어
npm start
// script 부분
"scripts": {
	"test": "echo \"Error: no test specified\" && exit 1",
	"server": "nodemon ./server/server.js", // 서버 실행 명령어
	"client": "npm start --prefix client", // client 내의 package.json에 있는 "script" : "start"
	"dev": "concurrently \"npm run server\" \"npm run client\""
}
  1. 설정이 완료되면 프로젝트 폴더 위치에서 npm run dev를 입력해 서버와 클라이언트가 모두 작동하는지 확인한다.

node and react 5.png

node and react 2.png