CRUD

react 와 node.js API연동

Jeungbin Han 2022. 7. 28. 00:34
{
    "name": "management",
    "version": "1.0.0",
    "scripts": {
        "client": "cd client && npm start",
        "server": "node server.js",
        "dev": "concurrently --kill-others-on-fail \"npm run server\" \"npm run client\""
    }, 
    "dependencies": {
        "body-parser": "^1.20.0",
        "express": "^4.16.4"
    },
    "devDependencies": {
        "concurrently": "^4.0.1"
    }
}

이것은 package.json파일이다. 

yarn dev 를 통해 client와 server를 동시에 시행한다. 

아래 글에서 이에 대해 자세히 설명하고 있다. 

> https://medium.com/free-code-camp/how-to-make-create-react-app-work-with-a-node-backend-api-7c5c48acb1b0

 

1. Create-react-app

 

npx create-react-app example-create-react-app-express

/client 이라는 저장소를 만든후 만들어진 모든 create-react-app을 client 저장소에 담는다. 

 

cd example-create-react-app-express
mkdir client

2. The Node Eepress Server

package.json 파일을 'example-create-react-app-express' 저장소에 담은후 아래내용을 카피한다. 

{
  "name": "example-create-react-app-express",
  "version": "1.0.0",
  "scripts": {
    "client": "cd client && yarn start",
    "server": "nodemon server.js",
    "dev": "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\""
  },
  "dependencies": {
    "body-parser": "^1.18.3",
    "express": "^4.16.4"
  },
  "devDependencies": {
    "concurrently": "^4.0.1"
  }
}

concurrently를 이용해 React와 Server를 같은시간에 작동시킨다. 

–kill-others-on-fail 은 다른 진행들을 끝어놓을 것이다. 

 

nodemon을 설치한다.

npm i nodemon -g
yarn

server.js 파일을 만든후 다음내용을 copy한다. 

... (이내용은 위에 있는 링크를 따라가면 볼수 있다. )

 

client 폴더 안에 (react파일이 있는 )들어 있는 package.json 에 

"proxy": "http://localhost:5000/"

이를 붙여 넣는다. 

...app.js 

 

그후에 yarn dev를 하면 server와 react가 연동이 된다.