이 포스트를 쓰기 전에 여러 블로그 포스트를 보고 왔습니다.

 

https://velog.io/@autumndr3ams/210802-React-Node.jsexpress-연결하기

https://baegofda.tistory.com/210

https://baegofda.tistory.com/211

 

일단 Node.js 가 설치되어 있다는 가정하에 진행을 하겠습니다.

 

1. 일단 작업 할 폴더(testReact)를 만든 뒤 cmd 또는 파워쉘을 키고 npx create-react-app client 를 쳐줍니다.

다음과 같이 나왔다면 제대로 설치된 것 입니다.

 

2. 그럼 폴더에 client 폴더가 있을건데 전 testReact 라는 폴더에 만들었으니 testReact 라는 폴더안에서 커맨드 창을 열고 server을 설치해줄겁니다.

 

일단 npm init 명령어를 친 다음 설정하신후 

npm install express 명령어를 쳐줍니다.

 

testReact 폴더 안에 server 라는 폴더를 만든 뒤 server 폴더 안에 server.js , Router 폴더와 api.js 를 만들어 줍니다.

그럼 폴더 구조가 이런식으로 될것입니다.

그리고 이제 코드를 작성할건데

 

server.js

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

const api = require("./Router/api");

app.use(express.json());
app.use("/api", api);

const port = 5000;

app.listen(port, () => {
  console.log(`Listening on port ${port}`);
});

 

Router/api.js

const express = require("express");
const router = express.Router();

router.get("/", (req, res) => {
  res.send({ api: "Welcome Hell" });
});

module.exports = router;

 

그리고 이제 server 쪽을 테스트 해볼것입니다.

 

node 명령어가 기본탑재 인데 불편한 부분이 있습니다.

업데이트 할때마다 서버를 껏다 킬수가 없기에 nodemon을 설치해줍니다.

 

그리고 concurrently 를 설치해줍니다.

concurrently 는 react 서버와 node 서버를 동시에 실행 시키기 위한 모듈 입니다.

 

npm install nodemon --save

npm install concurrently --save

 

그 뒤에 package.json에서 다음 scripts를 추가 해줍니다.

 

{
  "name": "testreact",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "server": "cd server && nodemon server",
    "client": "cd client && npm start",
    "start": "concurrently --kill-others-on-fail \"npm run server\" \"npm run client\""
  },
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "concurrently": "^7.0.0",
    "express": "^4.17.3",
    "nodemon": "^2.0.15"
  }
}

저장후 npm start를 해줍니다.

 

localhost:3000 , localhost:5000 으로 접속을 하여 문제가 없는지 확인해줍니다.

그리고 주소창에 localhost:5000/api 를 친다음 화면에 {"api": "Welcome Hell"} 이라고 나오면 정상적으로 작동하고 있는것입니다.

 

이제 client폴더에 가서 cmd 창을 열고 npm install http-proxy-middleware --save 를 쳐줍니다.

그리고 react에서 node.js와 통신을 하기 위해 axios를 설치해줍니다. npm install axios --save

그리고 코드를 수정해줍니다.

 

/client/src/App.js

import axios from "axios";
import { useEffect } from "react";

function App() {
  const callApi = async () => {
    axios.get("/api").then((res) => {
      console.log(res.data.api);
    });
  };

  useEffect(() => {
    callApi();
  }, []);

  return <div className="App"></div>;
}

export default App;

그리고 /client/src/setupProxy.js를 생성후

const { createProxyMiddleware } = require("http-proxy-middleware");

const apiUrl = "http://localhost:5000/";
const apiContext = ["/api"];

module.exports = (app) => {
  app.use(
    createProxyMiddleware(apiContext, {
      // 도메인 api로 호출
      target: apiUrl, // 통신할 서버의 도메인 주소
      changeOrigin: true,
    })
  );
};

다음과 같이 코드를 적어줍니다.

 

지금까지 했던것을 폴더 구조로 확인하자면 이런 형태가 나오게 됩니다.

 

 

그럼 console 창에서 Welcome Hell 이 나오는것을 볼수있습니다.

'FrontEnd > React' 카테고리의 다른 글

React - useEffect  (0) 2022.03.27
React - useRef DOM 제어  (0) 2022.03.25
React - Props  (0) 2022.03.23
React - State  (0) 2022.03.18
React 왜 배우는 것 일까?  (0) 2022.03.17

+ Recent posts