gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:36:39 24 4
gpt4 key购买 nike

我确信这个问题已经解决了,但我无法让它为我工作。

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

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

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

最佳答案

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

关于javascript - Express React 应用程序在本地运行,但在 heroku 部署时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54357546/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com