无法准备我的 MERN 应用以进行部署

问题描述

我之前从未将 MERN 应用部署到生产环境中。这将是我的第一次尝试,我计划将该应用部署到数字海洋。

因此,我已按照 Udemy 课程中的说明准备好要部署的 MERN 应用程序。我的应用程序结构如下:

enter image description here

以下是我对应用程序所做的主要更改:

  1. 因为在生产中不会有 create-react-app 创建的服务器,所以我在 server/index.js 中编写了生产路由逻辑,基本上说对于任何不由 app.use("/api/ users",userRoutes) & app.use("/api/download",downloadRoutes),后端服务器将为 client/build 文件夹内的 index.html 文件提供服务,该文件夹是我通过运行创建的命令:npm run build。

服务器/index.js

const express = require("express");
const path = require("path");
const dotenv = require("dotenv");
const colors = require("colors");
const connectDB = require("./config/db");
const {
  notFound,globalErrorHandler,} = require("./middleware/errorMiddleware");
const userRoutes = require("./routes/userRoutes");
const downloadRoutes = require("./routes/downloadRoutes");

dotenv.config();

connectDB();

const app = express();

app.use(express.json());

app.use("/api/users",userRoutes);
app.use("/api/download",downloadRoutes);

// Routing logic in production

if (process.env.NODE_ENV === "production") {
  app.use(express.static(path.join(__dirname,"/client/build")));

  app.get("*",(req,res) => {
    res.sendFile(path.resolve(__dirname,"client","build","index.html"));
  });
}

app.use(notFound);
app.use(globalErrorHandler);

const PORT = process.env.PORT || 5000;

app.listen(PORT,() => {
  console.log(`Server listening on port ${PORT}`.yellow.bold);
});

  1. 我已将 .env 文件中的 process.env.NODE_ENV 更改为 production。

经过上述更改后,当我运行“npm start”(仅启动后端服务器)(而不是同时启动前端和后端服务器的“npm run dev”)并访问http://localhost:5000 ,我应该看到我的应用程序。相反,我看到了以下错误

enter image description here

我做错了什么?

解决方法

正如您在错误消息中看到的那样,Express 正在寻找不存在的 index.html 内的 server/client/build。修正路径。

app.use(express.static(path.join(__dirname,'../client/build')))