리액트
react 프로젝트 만들기 & 서버 연동
kny_0
2022. 6. 7. 02:30
폴더 이동하기
cd 생성할 폴더 위치
프로젝트 생성
npx create-react-app 프로젝트이름
프로젝트 이름에 띄어쓰기 X
실행
npm start
vscode(에디터) 터미널에서 실행해 준다.
build하기
npm run build
리액트 완성본 html 파일이 build 폴더에 생성된다.
* 서버 만들기(Nodejs + Express)
-> nodejs 설치
-> 폴더 생성
-> server.js 파일 (server.js 옆에 서브폴더로 리액트 프로젝트 생성해야 됨)
const express = require('express');
const path = require('path');
const app = express();
app.listen(8080, function () {
console.log('listening on 8080')
});
-> 터미널 입력
npm init -y
npm install express
-> 서버 미리보기
nodemon server.js
node server.js
-> 리액트 폴더 만들기

*html 서버로 전송
//(server.js에 추가)
app.use(express.static(path.join(__dirname, 'react-project/build')));
app.get('/', function (요청, 응답) {
응답.sendFile(path.join(__dirname, '/react-project/build/index.html'));
});
react-project는 만든 리액트 프로젝트 이름이다.
build 후 html 파일은 index.html 파일 딱 하나(SPA)이므로 server.js에 추가해 주면 리액트와 nodejs 서버를 합칠 수 있다.
localhost:8080 으로 접속면 리액트 프로젝트가 나온다.
*리액트 라우팅
(server.js에 추가)
app.get('*', function (요청, 응답) {
응답.sendFile(path.join(__dirname, '/react-project/build/index.html'));
});
리액트 라우터로 작성한 코드를 /url로 실행하면 브라우저 url은 서버에게 요청하는 것이기 때문에 작동이 되지 않는다.
위코드를 항상 가장 하단에 작성하면 리액트 프로젝트를 보내주게 된다.
*DB 연동하기
npm install cors
app.use(express.json());
var cors = require('cors');
app.use(cors());
(client-side rendering) 서버 프로젝트에 다른 도메인주소끼리 ajax 요청을 주고 받을 때 필요한 cors 설치 후 nodejs 서버 파일 상단에 위 코드를 추가하면 리액트와 nodejs 서버간 ajax 요청이 가능하다.