首页 > 解决方案 > 在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}`);

标签: node.jsreactjsexpressherokumern

解决方案


推荐阅读