网站搜索

node.js - 在 Heroku 上使用 Mern 栈时重新加载不起作用


我已经使用这段代码将我的 MERN 技术栈部署到 Heroku 上:

import express from "express";
import path from "path";

const app = express();
const port = process.env.PORT || 5000;

app.get("/health-check", (req, res) => {
  res.sendStatus(200);
});

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(port, () => console.log(`Listening on port ${port}`));

我的网站和使用 react-router-dom 的路由工作得非常好。然而,我有两个问题无法解决。

  1. 当我重新加载页面时,我看到一个空白页面,并且控制台中出现这条消息和一个错误信息:

未找到(空白页显示此信息)

GET https://website.herokuapp.com/login 404(未找到)

  1. 当我第一次打开这个应用时,控制台打印出这个错误:

无法加载资源:服务器返回了 404 状态(未找到)

我完全不知道如何删除那些错误,因为我已经按照 StackOverflow 和 YouTube 上的所有答案操作了。

任何帮助都将不胜感激。

非常感谢。

答案#1

过了一会儿找到答案

因为我使用的是 TypeScript,并且我的索引文件在 src 文件夹内,我忘记回退一个级别。

"../client/build/index.html"

而不是

"./client/build/index.html"

完整的 index.ts:

if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/build"));
  app.get("*", (req, res) => {
    res.sendFile(path.join(__dirname, "../client/build/index.html"));
  });
}