这是我第一次尝试部署Mern堆栈。当我将其托管在Heroku上时,我的Mern应用程序(mongodb,express,react,node)未呈现(只是一个标题甚至为fav.icon的空页面)。我尝试了很多事情,但没有任何效果。我认为问题是Express应用程序无法正确托管静态内容。因为从chrome开发工具查看时所有资源都是空的
我在控制台中收到此错误
Uncaught SyntaxError: Unexpected token '<'
这是我的package.json
{
"name": "web_sever",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"heroku-postbuild": "cd client && npm install && npm build",
"client": "cd client && npm start",
"server": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.9.14",
"morgan": "^1.10.0",
"multer": "^1.4.2",
"nodemailer": "^6.4.6",
"nodemailer-smtp-transport": "^2.7.4",
"uuid": "^8.0.0"
},
"devDependencies": {
"nodemon": "^1.17.3"
}
}
这就是我在Express上托管静态内容的方式
app.use(cors());
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods: GET, POST,PUT,PATCH, OPTIONS");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.use('/public', express.static(__dirname + 'client/build'));
mongoose
.connect(mongouri, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("MongoDB Connected…");
})
.catch((err) => console.log(err));
app.use(morgan("dev"));
app.use("/uploads", express.static(path.join(__dirname, "/uploads")));
app.use(Parsbdy.json());
app.use("/admin", adminRoutes);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client/build/index.html'));
});
//custom error handling
app.use((req, res, next) => {
if (req.file) {
fis.unlink(req.file.path, (err) => {
console.log(err);
});
}
const Er = new Error("Not Found");
Er.status = 404;
next(Er);
});
//custom error handling
app.use((error, req, res, next) => {
res.status(error.status || 500);
res.json({
error: {
message: error.message,
},
});
});
app.listen(port, function () {
console.log(`Server is running on port: ${port}`);