【问题标题】:How can I get my MERN app to refresh correctly on heroku?如何让我的 MERN 应用程序在 heroku 上正确刷新?
【发布时间】:2020-09-03 13:52:21
【问题描述】:

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

【问题讨论】:

  • 我怀疑原因是因为您的单页应用程序仅位于根目录,您尚未设置 express 以从根目录以外的其他路由提供您的反应应用程序。请分享更多代码您如何使用express 设置路线
  • 这原来是一个不同的问题。看我的回答,指的是我后来发的帖子,终于解决了。

标签: javascript reactjs mongodb express heroku


【解决方案1】:

每当我刷新或 window.location() 时,我也会收到相同的错误“无法获取 /page”所以经过 3 天的试验和部署,我找到了这个解决方案。在部署之前将其添加到您的 server.js 文件中。

 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.listen 之前添加此代码 sn-p。请记住路径中的 ./client/build/index.html 引用了您在远程 heroku master 中的生产构建中的构建文件。

cannot get /page 发生是因为服务器无法找到使用 react-router 或前端中的其他任何东西创建的路由,因此我们需要将应用程序定向到生产构建中的 index.html 以便它启动整个再次前端进程并识别路由...

【讨论】:

    【解决方案2】:

    我的问题源于在我的 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}!`)
    );
    

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

    基本上有3个问题:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-05
      • 2021-03-03
      • 1970-01-01
      • 2020-04-18
      • 2020-06-05
      • 2022-10-01
      • 2021-11-23
      • 1970-01-01
      相关资源
      最近更新 更多