问题
I've finished working on my first MERN app. It works locally and it was 'successfully built' on Heroku but all that is displayed is the backend-data retrieved for the '/' route from MongoDB.
I've looked at a couple of resources that discuss deploying MERN stack apps to Heroku here: 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/
I've tried integrating these posts with my code but to no avail. I'm not sure how to use the path middleware in tandem with my three existing routes ('/', '/authors', and '/books') and ultimately how that results in the build for index.html. I'm not sure if it makes any difference but I'm using parceljs to build the frontend.
Edit: Added screenshot of folder layout to show where dist folder is located within the project
Below is my server.js file:
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);
回答1:
Can you try this code, if your app is in production express will serve static assets and it will redirect user to index.html if user comes to routes other than api routes(by providing app.get('*', ...))
server.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'))
})
}
来源:https://stackoverflow.com/questions/58073109/heroku-only-displaying-backend-of-mern-app-how-can-i-fix-this