首页 > 解决方案 > 如何让我的 MERN 应用程序在 heroku 上正确刷新?

问题描述

我将我的 MERN 应用程序部署到 heroku。它加载,我可以通过单击导航栏在页面之间导航。但是,如果我刷新一个页面,它就会出现空白。屏幕或控制台上没有错误消息。如果我回到以前工作的上一页,它也会出现空白。在这一点上,我不知道要寻找什么。

标签: javascriptreactjsmongodbexpressheroku

解决方案


我的问题源于在我的 server.js 文件中错误地定义了根反应路由。我让主页呈现和刷新,但应用程序不会加载任何其他页面。这是此时的 server.js 文件:

const express = require("express");
const mongoose = require("mongoose");
const routes = require("./routes");
const app = express();
// set the port for mongo connection to 3001 in development mode
const PORT = process.env.PORT || 3001;

// Configure body parsing for AJAX requests
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Serve up static assets
if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/build"));
  app.get("*", function (req, res) {
     res.sendFile(path.join(__dirname, "./client/build/index.html"));
});
}

app.use(routes);

mongoose.connect(
  process.env.MONGODB_URI || "mongodb://localhost/portfolio_db",
  {
    useCreateIndex: true,
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false,
  }
);

// Start the API server on port 3001
app.listen(PORT, () =>
  console.log(`  ==> API Server now listening on PORT ${PORT}!`)
);

这种解决了我的问题,但应用程序仍然没有正确路由,所以我发布了这个:新问题

基本上,有3个问题:

  1. 文件顶部不需要“路径”,因此未定义 index.html 的路径(必须查看 heroku 日志才能看到此错误)。
  2. 默认的反应路由 (app.get('*'....)) 不应该在 if 语句中,并且
  3. 默认的 react route 语句需要位于 'app.use(routes)' 语句的下方。

我还删除了 /routes/index.js 中定义默认反应路由的语句。现在应用程序正确部署和路由。


推荐阅读