[React] React와 Node.js연결하기

·2023년 4월 26일
0

투두리스트 웹앱

목록 보기
2/2
post-thumbnail

1. react build


client 폴더에서 다음 명령어를 실행한다.
작성한 react 코드들을 배포 버전으로 만들어주는 과정이다.

$ npm run build

build 폴더가 생성된 것을 확인할 수 있다.



2. Server 만들기



client와 같은 위치에 server 폴더를 생성한다.

server 폴더 아래에 index.js를 생성한 뒤 다음과 같이 적는다.

const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");

const app = express();
const port = 3000;

app.use(bodyParser.urlencoded({ extended: true }));

app.use(express.static(path.join(__dirname, "../client/build")));

app.get("/", function (req, res) {
  res.sendFile(path.join(__dirname, "/client/build/index.html"));
});

app.listen(port, () => {
  console.log("Server started...");
});


코드를 수정할 때마다 서버를 재시작 하는 것은 번거롭다.
nodemon은 코드가 변경될 때마다 이 작업을 자동으로 해준다.


nodemon을 설치한 후
$ npm install nodemon


package.json

"dev": "nodemon index.js",

을 추가한다.

이제 npm run dev라는 명령어로 서버를 시작할 수 있다.

서버를 시작한 뒤 http://localhost:3000/로 접속했을 때

이 화면이 뜨면 성공이다.

0개의 댓글