部署后如何解决Heroku中的页面未找到错误

时间:2019-03-23 19:56:20

标签: node.js express heroku

我正在尝试将express / node.js应用程序上传到heroku。该应用程序已成功部署,但是当我尝试访问URL时,出现错误:未找到

运行 heroku日志--tail 时,我得到:

Error: ENOENT: no such file or directory, stat '/client/build/index.html'

所以我认为目录和statics文件夹有问题

这是我的server.js文件:

const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const cors = require("cors");
const path = require("path");

const users = require("./routes/api/users");
const profile = require("./routes/api/profile");
const matches = require("./routes/api/matches");

const app = express();

//body-parser middleware
app.use(bodyParser.urlencoded({ extended: false, limit: "50mb" }));
app.use(bodyParser.json({ limit: "50mb" }));

//db config
const db = require("./config/keys").mongoURI;

//cors
app.use(cors());

//connect to mongoose
mongoose
 .connect(db, { useNewUrlParser: true })
 .then(() => console.log("MongoDB connected"))
 .catch(err => console.log(err));

//Passport middleware
app.use(passport.initialize());

app.use("/images", express.static(path.join(__dirname + "/images")));

//Passport config
require("./config/passport")(passport);

//Use route
app.use("/api/users", users);
app.use("/api/profile", profile);
app.use("/api/matches", matches);

//Serve static assets if in production
if (process.env.NODE_ENV === "production") {
  app.enable("trust proxy");

  //Set static folder
  app.use(express.static(path.join(__dirname, "/../client/build")));

  app.get("*", (req, res) => {
    res.sendFile(path.join(__dirname + "/../client/build/index.html"));
  });
}

const port = process.env.PORT || 5000;

app.listen(port, () => console.log(`server running on port ${port}`));

我还提供了“位置”文件夹的图片folders

3 个答案:

答案 0 :(得分:1)

我通过在package.json中定义build和install命令解决了这个问题。 Heroku会在那里寻找生产的构建命令。

"scripts": {
    "build": "cd client && npm run build",
    "install": "cd client && npm install",
    "start": "node server",
    "server": "nodemon server",
    "client": "npm start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\""
  },

答案 1 :(得分:0)

我认为应该是这样

app.use("/images", express.static(path.join(__dirname + "images")));

编辑:实际上,您的应用希望在/../client/build/index.html处找到一个文件,但该文件不存在(这是ENOENT错误的意思)。因此,您要么需要创建预期的目录结构,要么配置您的应用程序,以使其在index.html的正确目录中查找。那就是我现在所了解的,希望对您有所帮助。

答案 2 :(得分:0)

我也遇到了类似的错误。对我来说,问题是我在 package.json 文件中有错误的构建脚本,所以构建根本没有创建。

验证您在 package.json 文件中有“heroku-postbuild”脚本,如下所示。

"scripts": {
"start": "node server.js",
"server": "nodemon server.js",
"client": "npm start --prefix client",
"clientinstall": "npm install --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client" 
},