Express React 应用程序在本地运行,但在 heroku 部署时出错

IT技术 javascript node.js reactjs heroku
2021-05-16 06:34:45

我确定这已经解决了,但我无法让它为我工作。

在本地我的 repo 以此作为我的

/index.js

const express = require("express");
const keys = require("./config/keys");
const path = require("path");

const app = express();

app.use(express.static(__dirname));
app.use(express.static(path.join(__dirname, "public")));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// uses fuzeRoutes
require("./routes/routes")(app);

app.get("*", function(req, res) {
  res.sendFile(__dirname, "public", "index.html");
});

app.listen(process.env.PORT || 5000, function() {
  console.log(
    "Express server listening on port %d in %s mode",
    this.address().port,
    app.settings.env
  );
});

包.json

  "scripts": {
    "client-install": "npm install --prefix client",
    "start": "node index.js",
    "server": "nodemon index.js",
    "client": "npm run start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\"",
    "heroku-postbuild": "cd client && npm install && npm run build"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.18.0",
    "concurrently": "^4.1.0",
    "express": "^4.16.4",
    "http-proxy-middleware": "^0.19.1",
    "nodemon": "^1.18.9"
  }

现在这在本地工作没有问题,但在 heroku 部署上我得到一个错误 at=error code=H13 desc="Connection closed without response" method=GET path="/"

浏览其他问题我看到它是由于"SSL termination occurs at Heroku's load balancers; they send your app plain (non-SSL) traffic, so your app should create a non-HTTPS server."浏览了其他问题,我要么不理解该解决方案,要么找不到正确的线程。

任何帮助,将不胜感激

更新:

我能够解决 H13 错误的问题。

问题是:

app.use(express.static(path.join(__dirname, "public")));
//
//
//
app.get("*", function(req, res) {
  res.sendFile(__dirname, "public", "index.html");
});

本来应该 :

   app.use(express.static(path.join(__dirname, "client/public")));
    //
    //
    //
    app.get("*", function(req, res) {
      res.sendFile(__dirname,"client", "public", "index.html");
    });

现在的问题是部署时我收到 200 状态代码,at=info method=GET path="/"但页面返回空白。页面的 HTML 显示它<div id="root">在构建路径中有一个,但页面没有加载react组件。

1个回答

我已将以下快速配置部署到 Heroku 到 create-react-app 应用程序:

app.use(express.static(path.join(__dirname, './client/public')))

app.get('*', function(_, res) {
  res.sendFile(path.join(__dirname, './client/public/index.html'), function(err) {
    if (err) {
      res.status(500).send(err)
    }
  })
})

您可以在此处查看完整代码