React + NodeJS + Mongodb , heroku로 배포하는 법, (heroku Cannot GET /)

Gayoung Lee·2022년 2월 19일
0

heroku

목록 보기
2/2
post-thumbnail

Intro

  • 저번 포스팅에선, json-server를 포함한 간단한 프로젝트의 heroku 를 통한 배포를 다뤘습니다. 이번 포스팅에선 React + NodeJS + Mongodb 기반의 프로젝트를 heroku를 통해 배포하는 과중 중 제가 오류를 해결했던 방법에 대해 정리해보겠습니다.

React + NodeJS + Mongodb 기반의 프로젝트 , heroku로 배포하는 법

  • 전체적인 참조는 https://leonkong.cc/posts/express-with-react.html 글을 참고했습니다. 이후 생기는 오류를 해결하기 위해 제가했던 방법들에 대한 포스팅 입니다.

  • 전체 디렉토리 구조는 아래와 같습니다.

client
ㄴpublic
ㄴsrc
ㄴpackage.json
server
ㄴserver.js
package.json
  • 저의 경우 최상위 디렉토리의 package.json에서의 수정사항이 있었습니다. heroku-postbuild를 추가해주세요!
  "scripts": {
    "heroku-postbuild": "cd client && npm install && npm run build",
    ...
  },
  • proxy를 사용해 react의 3000번 port와, node의 5000번 port 를 합쳐주었는데 본인 프로젝트의 server.js에 app.listen 코드 부분이 있다면 아래와 같이 process.env.PORT를 추가해 주세요.
app.listen(process.env.PORT || 5000, function () {
  ...
});
  • 마지막으로 배포했을 때 Cannot GET / 오류가 나올때의 저의 해결방안 입니다. server.js에 다음 코드를 추가해주세요.
if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/build"));
}

app.get("/", (request, response) => {
  response.sendFile(path.join(__dirname, "client/build", "index.html"));
});

Outtro

😊

profile
삽질하며 성장하는 gayoungee

0개의 댓글