Node.js와 React 연결하기

이은지·2022년 1월 5일
0

Node.js

서버를 만드는 툴

서버란? 특정 url로 접속하면 특정 파일을 보내주는 애

React

HTML 파일을 만들어주는 툴 근데 이제 예쁜 웹앱 HTML

리액트가 만드는 HTML 파일은 index.html 한 개임! index.html 안에서 JavaScript를 이용해 각종 HTML을 갈아끼우는 것(Single Page Application)

Node.js와 React의 연결

누군가 메인페이지에 접속하면 React로 만든 HTML을 보내주는 것

💁🏻‍♂️ 메인페이지 접속 시 HTML 보내주기

🔹 서버 만드는 코드

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

const http = require("http").createServer(app);
http.listen(8080, function () {
  console.log("listening on 8080");
});
// 8080을 8090으로 바꾸면 localhost:8090에 서버가 띄워짐!

🔹 미들웨어

html, css, js, img 파일들이 담긴 곳을 명시

app.use(express(static()))

app.use( express.static( path.join(__dirname, 'public') ) )
// __dirname: 현재 경로
// 현재 경로에서 public 폴더 안에 있는 static 파일을 사용하겠다는 뜻

🔹 HTML을 보내주는 함수

app.get("/", function (req, res) {
  res.sendFile(path.join(__dirname, "public/index.html"));
});
// "/" 라는 url로 접속하면
// 현재 경로에서 public 폴더 안에 있는 index.html을 보내주겠다

🔹 최종 코드

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

const http = require("http").createServer(app);
http.listen(8080, function () {
  console.log("listening on 8080");
});

app.use(express.static(path.join(__dirname, "public")));

app.get("/", function (req, res) {
  응답.sendFile(path.join(__dirname, "public/main.html"));
});

💁🏻‍♀️ 메인페이지 접속 시 리액트 HTML 보내주기

React로 만든 SPA를 연결하는 것도 그리 어렵지 않다!

  1. React로 코드를 작성한 다음 터미널 창에 npm run build 입력
  2. 생성된 build 폴더 내의 index.html을 server.js에서 연결해주면 된다.
/* eslint-disable */
const express = require("express");
const path = require("path");
const app = express();

const http = require("http").createServer(app);
http.listen(8080, function () {
  console.log("listening on 8080");
});

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

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

__dirname : 현재 server.js 파일이 위치한 경로

이 경로를 기준으로 build 파일 내의 index.html 경로를 적어주면 된다.


결과: localhost:8080으로 접속하면 App.js에 담긴 내용이 뜬다!

0개의 댓글