React와 Node를 axios로 연결하기

Jamkris (승현)·2023년 4월 18일
3

Little Tips

목록 보기
2/5
post-thumbnail

리액트 프로젝트 생성하기

npx create-react-app frontend

Packgae.json 생성

npm init

express 다운

npm i express

sever.js 파일만들기

최상위 풀더에 src 풀더를 만들고 server.js 파일 생성

import express from "express"
import api from "./api"

const app = express();
const PORT = 5000;

app.listen(PORT, () => console.log(`${PORT} 포트에서 서버 작동~`))

nodemon, babel 설치

Why?
nodemon은 서버에 변동사항이 있을때마다 자동적으로 서버 재부팅을 해줍니다. 이게 없으면 매번 서버를 껐다 켜야하기에 굉장히 불편하다.
babel은 컴파일 시 es6문법을 이전 버전으로 변동하여 최신 문법을 사용하더라도 서버가 인식할 수 있도록 해주는 패키지이다.

npm i nodemon

한번에 하나씩 쓰자

npm i @babel/preset-env @babel/core @babel/node

babel.config.json 파일 생성

최상위 폴더에 babel.config.json 파일 생성

{
    "presets": ["@babel/preset-env"]
}

Package.json 수정

{
  "name": "linknodereact",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start:back": "nodemon --exec babel-node src/server.js",
    "start:front": "cd frontend && npm run start"
  },

  "author": "",
  "license": "ISC",
  "dependencies": {
    "@babel/core": "^7.21.4",
    "@babel/node": "^7.20.7",
    "@babel/preset-env": "^7.21.4",
    "nodemon": "^2.0.22"
  }
}

api.js 파일 생성

src 풀더 안에 생성

import express from "express";

const router = express.Router();

router.get("/", (req, res) => {
    res.send("Hello API")
});

export default router;

package.json 수정

frontend 폴더에 package.json 파일에 구문 추가하기

  "proxy": "https://localhost:5000"

axios 설치

"frontend" 오타남 ㅋㅋ
쨌든 frontend에 axios 설치

cd frontend
npm i axios

react App.js 수정

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


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

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

  return <div>프론트 페이지</div>;
}

export default App;

실행

npm run start:front (프론트)
npm run start:back (백엔드)

GitHub

여기

profile
Nothing Change If You Don't Try

0개의 댓글