首页 > 解决方案 > 在 heroku 上托管 React + Node.js 应用程序时出现问题

问题描述

当我在本地处理我的项目时(没有问题),我在端口 3000 上运行 npm start,我还必须打开另一个终端并在端口 4000 上运行 node server/server.js。然后我就可以工作了用我的浏览器连接我的前端和后端。现在我正在尝试在 heroku 上托管这个项目,但没有运气。这是我的错误:

2020-08-26T11:54:23.905587+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/" host=whatever.herokuapp.com request_id="whatever" fwd="96.20.56.73" dyno=web.1 connect=1ms service=159ms status=503 bytes=0 protocol=https

和 package.json:

    {
  "name": "library",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:4000",
  "dependencies": {
    "@material-ui/core": "^4.9.9",
    "@material-ui/icons": "^4.9.1",
    "@material-ui/lab": "^4.0.0-alpha.48",
    "@material/react-snackbar": "^0.15.0",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.4.0",
    "@testing-library/user-event": "^7.2.1",
    "chai": "^4.2.0",
    "clsx": "^1.1.0",
    "cookie-parser": "^1.4.4",
    "dotenv": "^8.2.0",
    "google-maps-react": "^2.0.2",
    "hookrouter": "^1.2.3",
    "i18next": "^19.4.1",
    "i18next-browser-languagedetector": "^4.0.2",
    "i18next-xhr-backend": "^3.2.2",
    "immer": "^5.3.6",
    "mongo-seeding": "^3.4.1",
    "mongodb": "^3.5.3",
    "multer": "^1.4.2",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-facebook-login": "^4.1.1",
    "react-google-login": "^5.1.1",
    "react-hook-google-maps": "0.0.3",
    "react-i18next": "^11.3.4",
    "react-redux": "^7.1.3",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.4.0",
    "redux": "^4.0.5",
    "redux-immer": "^1.0.4",
    "sha1": "^1.1.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "mocha --exit",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "eslint": "^6.8.0",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-react": "^7.19.0",
    "eslint-plugin-react-hooks": "^3.0.0",
    "eslint-plugin-react-redux": "^3.0.3",
    "mocha": "^7.2.0",
    "supertest": "^4.0.2"
  }
}```

是代理的原因吗?或者我有错误的启动脚本?或者是其他东西?

标签: node.jsreactjsheroku

解决方案


我在heroku上部署的方式是:

  1. 到我添加的后端 package.json 脚本
"heroku-postbuild": "cd client && npm install && npm install --only=dev --no-shrinkwrap && npm run build"
  1. 将以下内容添加到我的 server.js
if (process.env.NODE_ENV === "production") {
  app.use(express.static(path.join(__dirname, "client/build")));
  app.get("*", (request, response) => {
    response.sendFile(path.join(__dirname, "client/build", "index.html"));
  });
}

在这些之后,我只是在git push heroku master没有任何问题的情况下部署它。


推荐阅读