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

IT技术 node.js reactjs deployment web-deployment mern
2021-05-19 23:09:31

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

因此,我按照 Udemy 课程中的说明准备了我的 MERN 应用程序以进行部署。我的应用程序结构如下: 在此处输入图片说明 以下是我对我的应用程序所做的主要更改:

  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时,我应该看到我的应用程序。相反,我看到以下错误。

在此处输入图片说明 我究竟做错了什么?

1个回答

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

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