首页 > 解决方案 > Heroku 仅显示 MERN 应用程序的后端。我怎样才能解决这个问题?

问题描述

我已经完成了我的第一个 MERN 应用程序。它在本地工作,并且在 Heroku 上“成功构建”,但显示的只是从 MongoDB 的“/”路由检索到的后端数据。

我在这里查看了一些讨论将 MERN 堆栈应用程序部署到 Heroku 的资源:1. https://www.freecodecamp.org/forum/t/solved-deployment-problem-showing-backend/280178 2. https: //www.freecodecamp.org/news/how-to-deploy-a-react-app-with-an-express-server-on-heroku-32244fe5a250/

我尝试将这些帖子与我的代码集成,但无济于事。我不确定如何将路径中间件与我的三个现有路由(“/”、“/authors”和“/books”)结合使用,以及最终如何生成 index.html。我不确定它是否有任何区别,但我正在使用 parceljs 构建前端。

编辑:添加了文件夹布局的屏幕截图以显示 dist 文件夹在项目中的位置

下面是我的 server.js 文件:

if (process.env.NODE_ENV !== "production") {
  require("dotenv").config();
}

const express = require("express");
const app = express();
const cors = require("cors");
const path = require("path");

// Middleware
app.use(express.urlencoded({ limit: "10mb", extended: true }));
app.use(express.json({ limit: "10mb" }));
app.use(cors());

// Connect to Mongoose
const mongoose = require("mongoose");
mongoose.connect(process.env.MONGO_URI, {
  useNewUrlParser: true,
  useCreateIndex: true,
  useUnifiedTopology: true
});

const db = mongoose.connection;
db.on("error", err => console.error(err));
db.once("open", () => console.log("Connected to Mongoose"));

// Define routes
const indexRouter = require("./routes/index");
const authorRouter = require("./routes/authors");
const bookRouter = require("./routes/books");

// Utilize routes
app.use("/", indexRouter);
app.use("/authors", authorRouter);
app.use("/books", bookRouter);

app.listen(process.env.PORT || 3000);

标签: node.jsreactjsexpressherokuparceljs

解决方案


你能试试这个代码吗,如果你的应用程序在生产中,express 将提供静态资产,如果用户访问 api 路由以外的路由,它会将用户重定向到 index.html(通过提供 app.get('*', ...) )

服务器.js

...

app.use("/books", bookRouter);

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

推荐阅读