[react] react에서 json-server 설치, 실행, 배포 (heroku) 요약

Dan·2022년 12월 9일
0

React

목록 보기
4/6

설치

  • yarn add json-server

실행

  • yarn json-server --watch db.json --port 3001

db.json (root에 파일 만들어줌) 예시

{
  "todos": [
    {
      "id": 1,
      "title": "json-server",
      "content": "json-server를 배워봅시다."
    }
  ]
}

브라우저 주소창에 localhost:3001/todos 결과


    {
      "id": 1,
      "title": "json-server",
      "content": "json-server를 배워봅시다."
    }

json-server를 사용할 때 url 경로로 object를 탐색함

배포

  • CRA로 새로운 프로젝트 생성
  • 프로젝트 최상위에 server폴더 생성
    • index.js, db.json 추가

      // server/index.js	
      const jsonServer = require("json-server");
      const path = require("path");
      
      const server = jsonServer.create();
      const router = jsonServer.router(path.resolve(__dirname + "/db.json"));
      const middlewares = jsonServer.defaults({
        static: path.resolve(__dirname + "/../build/"),
      });
      
      const port = process.env.PORT || 3001;
      
      server.use(middlewares);
      
      server.use(jsonServer.bodyParser);
      
      server.use(router);
      server.listen(port, () => {
        console.log("JSON Server is running");
      });
      // server/db.json
      {
        "todos": [
          {
            "id": 1,
            "title": "json-server",
            "content": "json-server를 배워봅시다."
          }
        ]
      }
  • cross-env 설치 yarn add cross-env
  • package.json 수정
    "scripts": {
        "start": "node server",
        "start:dev": "cross-env NODE_PATH=src react-scripts start",
        "build": "cross-env NODE_PATH=src react-scripts build",
        "test": "react-scripts test --env=jsdom",
        "eject": "react-scripts eject",
        "heroku-postbuild": "cross-env NODE_PATH=src npm run build"
      },
    
  • 테스트 해보기
    • 빌드 : yarn build
    • 서버 실행 : node server
  • heroku 설치
    • brew tap heroku/brew && brew install heroku
    • 설치 확인 : heroku -v
  • heroku 회원가입
    • 터미널에서 heroku login
    • 팝업 사이트에서 회원가입
    • 2022/11/28 부터 카드 등록해야함 (validation목적)
    • 터미널에서는 아마 로그인 된 상태일것 안되어 있으면 다시 heroku login
  • heroku repo로 push & 배포
    git init 
     
    git add . 
    
    git commit -m "initial commit"
    
    heroku create <프로젝트명> # 프로젝트명을 공백으로 하면 랜덤 이름 설정
    
    heroku config:set NPM_CONFIG_PRODUCTION=false # devDependency 도 설치하게 설정
    
    git push heroku main 
  • push 메세지 중에 url 나옴 (push 꽤 오래걸림 1-2분)
  • url/todos → 데이터 확인 가능

0개의 댓글