[Node.js] node.js + express / React 프로젝트 연동

yellowbutter·2024년 9월 5일

NodeJs

목록 보기
8/8
post-thumbnail

node.js

  1. nodejs 검색, 설치
  2. 작업폴더 만들고 에디터 오픈
  3. server.js 만들고 코드 적어넣기
const express = require('express');
const path = require('path');
const app = express();

app.listen(8080, function () {
  console.log('listening on 8080')
}); 
  1. npm init -y
  2. npm install express
  3. npm install cors
app.use(express.json());
var cors = require('cors');
app.use(cors());

react

  1. 프로젝트 세팅
  2. npm run build
  3. node.js에 폴더 넣어두기

app.use(express.static(path.join(__dirname, 'react-project/build')));

app.get('/', function (요청, 응답) {
  응답.sendFile(path.join(__dirname, '/react-project/build/index.html'));
});
  • nodemon server.js 로 실행

react router 사용할 경우

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

이 코드는 항상 가장 하단에 놓아야 잘된다.

db 데이터 보내줄때

react로는 데이터를 db -> 서버 -> 리액트로 그대로 전송함.

서브디렉토리에 리액트앱 발행하고 싶은 경우

현재 메인페이지가 리액트앱인데

/react 이렇게 접속하면 리액트로 만든 html,

/ 이렇게 접속하면 public 폴더에 있던 그냥 main.html

보여주고 싶은 경우

(server.js)

app.use( '/', express.static( path.join(__dirname, 'public') ))
app.use( '/react', express.static( path.join(__dirname, 'react-project/build') ))

app.get('/', function(요청,응답){
  응답.sendFile( path.join(__dirname, 'public/main.html') )
}) 
app.get('/react', function(요청,응답){
  응답.sendFile( path.join(__dirname, 'react-project/build/index.html') )
})
//리액트프로젝트 내의 package.json
{
  "homepage": "/react",
  "version": "0.1.0",
  ...} 
  • 리액트 프로젝트 package.json에 homepage

    => 발행을 원하는 서브디렉토리명으로 새로 기입

    그럼 server.js 에서 /react 접속시 리액트 프로젝트보내고

    / 접속시 일반 html 파일 내보냄

profile
기록은 희미해지지 않는다 🐾🧑‍💻

0개의 댓글