将React应用程序部署到heroku无法连接后端



我正在尝试将我的应用程序部署到Heroku,该应用程序使用node.js、react和MongoDB;部署成功;但是,该网站无法从MongoDB中获取数据。错误是GET http://localhost:5000/comment net::ERR_CONNECTION_REFUSEDUncaught (in promise) Error: Network Error,我想这是因为我没有在后端运行node server.js。有人能帮助我如何正确部署吗?我的后台包.json是

"client-install": "npm install --prefix myprofile",
"start":"node server.js",
"server":"nodemon server.js",
"client":"npm start --prefix myprofile",
"dev":"concurrently "npm run server" "npm run client"",
"heroku-postbuild":"NPM_CONFIG_PRODUCTION=false npm install --prefix myprofile && npm run build --prefix myprofile"
}

我的server.js是

const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const path = require("path");
require("dotenv").config();
const app = express();
const port = process.env.PORT || 5000;
app.use(express.json());
app.use(cors());
//app.use(express.static(path.join(__dirname,'./myprofile/build')));
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
const connection = mongoose.connection;
connection.once("open", () => {
console.log("MongoDB data connected");
});
const CommentRouter = require("./CommentRouter");
app.use("/comment", CommentRouter);
if (process.env.NODE_ENV === "production") {
app.use(express.static("myprofile/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "myprofile", "build", "index.html"));
});
}
app.listen(port, () => console.log(`Server is running on ${port}`));

提前非常感谢!

如果要将此项目部署到heroku,则start命令和server.js看起来与此示例相似,因此这是一个良好的开端。

您是否使用heroku设置环境变量,特别是process.env.ATLAS_URI?我想heroku不知道MongoDB数据库的位置。

最新更新