카테고리 없음

node.js와reactjs 연동하기 실습

Break-Limits 2023. 6. 2. 11:33

시작하기


참고

 

서버는 누가 html 파일 요청하면 보내주는 간단한 프로그램입니다.

  • 작업폴더생성
  • server.js 생성 및 코드 작성
  • package.json 설치 [npm init -y]
  • express 모듈 설치 [npm install express  ]
  • nodemon 설치 ,  package.json에 script 추가          "start": "nodemon app"
  • npm start

 

node.js에서 서버실행

const express = require("express");
const path = require("path");

const app = express();
// app.set("port", process.env.PORT || 8080);   //포트를 env파일로 관리할 경우 [env 환경없을경우 포트 8080 설정]

app.get("/", (req, res) => {
  res.send("Hello");
}); //path "/"로 클라이언트 요청및 서버 응답

app.listen(8080, () => {
  console.log("8080번 포트에서 대기중.");
});

 

 - 정상 동작하는지 확인.

 

 

리액트 프로젝트 생성 


 

server.js  서브폴더로 frontend 폴더 생성

  

 

react  초기생성

npx create-react-app 프로젝트명

* 프로젝트명 으로 폴더 생성 

* npx는 NPM 패키지를 실행하기 위한 도구로, 필요한 패키지가 로컬에 설치되어 있지 않더라도 실행할 수 있습니다. npx를 사용하면 패키지를 다운로드하고 실행하는 과정이 자동으로 처리됩니다.

 

 

react 시작

리액트 프로젝트  폴더에서 실행.

npm run start

 

페이지 제작

[app.js]

import First from "./pages/first";
import Second from "./pages/second";
import Third from "./pages/third";
import Forth from "./pages/forth";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
function App() {
  return (
    <div className="App">
      <header className="App-header"></header>
      <Router>
        <Routes>
          <Route path="/first" element={<First />} />
          <Route path="/second" element={<Second />} />
          <Route path="/third" element={<Third />} />
          <Route path="/forth" element={<Forth />} />
        </Routes>
      </Router>
    </div>
  );
}

export default App;

 

src 폴더에 pages 폴더 생성및 페이지 추가

 

* pages폴더가 src 폴더 내부에 위치해야함. build시 error 발생. 리액트에서 외부 모듈 지원안함.

 

[first.js]

import React from "react";

function first() {
  return (
    <div>
      <h1>MY FIRST PAGE</h1>
      <p style={{ color: "red" }}>this is the first page.</p>
    </div>
  );
}

export default first;

[second.js]

import React from "react";

function first() {
  return (
    <div>
      <h1>MY SECOND PAGE</h1>
      <p style={{ color: "yellow" }}>this is the second page.</p>
    </div>
  );
}

export default first;

..... third.js와 forth.js 는 위와 같은 형태임.

 

 

개발완료및 배포

npm run build

 

-> 리액트 완성본 html 파일이 build 폴더내에 생성됨.


 

node.js에서 react에서 생성한 페이지를 연동.

리액트 프로젝트 폴더 내부의 build 폴더를 server.js 폴더 쪽으로 복사및 붙여넣기.

 

.....

(server.js에 추가)
app.use(express.static(path.join(__dirname, '/build)));

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

......

 

 

 

 

클라이언트가 요청하는 url 전체를 리액트가 처리

 

브라우저 URL창에 때려박는건 서버에게 요청하는거지 리액트 라우터에게 라우팅 요청하는게 아님.

(server.js에 추가)

app.get('*', function (요청, 응답) {
  응답.sendFile(path.join(__dirname, '/build/index.html'));
});