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

时间:2019-01-25 00:50:32

标签: javascript node.js reactjs heroku

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

在本地,我的存储库将其作为我的

/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
  );
});

package.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");
    });

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

1 个答案:

答案 0 :(得分:0)

我已将以下快速配置部署到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)
    }
  })
})

您可以看到完整的code here