javascript - 如何让我的 MERN 应用程序在 heroku 上正确刷新?
问题描述
我将我的 MERN 应用程序部署到 heroku。它加载,我可以通过单击导航栏在页面之间导航。但是,如果我刷新一个页面,它就会出现空白。屏幕或控制台上没有错误消息。如果我回到以前工作的上一页,它也会出现空白。在这一点上,我不知道要寻找什么。
解决方案
我的问题源于在我的 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个问题:
- 文件顶部不需要“路径”,因此未定义 index.html 的路径(必须查看 heroku 日志才能看到此错误)。
- 默认的反应路由 (app.get('*'....)) 不应该在 if 语句中,并且
- 默认的 react route 语句需要位于 'app.use(routes)' 语句的下方。
我还删除了 /routes/index.js 中定义默认反应路由的语句。现在应用程序正确部署和路由。
推荐阅读
- javascript - React下载excel文件保留样式
- python - 为什么我还有系统解释器?
- c# - 将 php 脚本翻译成 c# httpClient
- maven - 如何运行 SOAP ui 测试部分的 Maven 安装?
- windows - 我的 git 存储库更改经常被标记为假设不变
- javascript - 带 {} 的 Var 打破 IE 11
- botframework - 由于没有身份验证标头,无法连接到机器人
- react-native - 从 React Native 中本地创建的 .json 文件中获取用户名和密码
- python-3.x - 如何使用 elasticsearch-dsl-py 创建“或”条件过滤器?
- php - PHP网络副本 - 无法打开流,权限被拒绝,但可以从控制台工作