node.js - 在heroku中构建和部署后清空反应应用程序
问题描述
这是我第一次尝试部署一个 mern 堆栈。当我在 heroku 上托管它时,我的 mern 应用程序(mongodb、express、react、node)没有呈现(只是一个标题甚至没有 fav.icon 的空页面)。我尝试了很多东西,但没有任何效果。我认为问题在于快递应用程序没有正确托管静态内容。因为从 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}`);
解决方案
推荐阅读
- python - Keras 多元时间序列预测模型返回 NaN 作为 MAE 和损失
- javascript - 在我的项目中(随机报价生成器)。我无法对问题进行排序?
- javascript - 如何阻止兄弟组件重新渲染?
- kubernetes - k8s 如何关联 ReplicaSet 和 Pod?
- heroku - 与heroku中的日志流断开连接
- python - 在python中计算每五秒的平均值
- r - 使用 ff 包时出错 ff 中的错误(initdata = initdata,.. 写入错误)
- postgresql - 如何在 Ubuntu 上安装 Postgres 并创建超级用户?
- amazon-web-services - 如何将文件直接下载到 s3 对象中
- vue.js - 带有浏览器构建的 Vue 3 日期选择器?