node.js - 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);
解决方案
你能试试这个代码吗,如果你的应用程序在生产中,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'))
})
}
推荐阅读
- python - 使用 spacy-langdetect 的多处理(n_process > 1)的 spaCy nlp.pipe 错误
- python - 在 python 中使用 teradatasql 时,如何解决连接池句柄 = 1 错误?
- actions-on-google - actions_intent_MEDIA_STATUS 事件未在生产版本上发送
- java - 如何在 Spring Boot 的映射器接口中使用 @Autowired 正确实例化一个类?
- django-rest-framework - 使用 http only cookie 来存储身份验证令牌 django-rest-framework
- javascript - 解码打字稿三元运算符
- rust - 我可以依赖两个相同结构的序列化是相同的吗?
- java - Spring对象有时在Websphere中抛出空指针异常但不是Tomcat
- javascript - PDF 原始数据 - 这是什么?以及如何使用它在 iframe 或 PDF.js 查看器中显示
- javascript - 使用 document.queryselector all 找不到类元素