【问题标题】:Not able to prepare my MERN app for deployment无法准备我的 MERN 应用程序以进行部署
【发布时间】:2021-03-26 03:52:56
【问题描述】:

我之前从未将 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 更改为生产环境。

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

我做错了什么?

【问题讨论】:

    标签: node.js reactjs deployment web-deployment mern


    【解决方案1】:

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

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

    【讨论】:

    猜你喜欢
    • 2021-03-03
    • 2018-12-18
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多