fac*_*ger 5 heroku node.js express
我正在尝试将express/node.js 应用程序上传到heroku。该应用程序已成功部署,但当我尝试访问该网址时,出现错误: Not Found。
当我运行heroku log --tail时,我得到:
Error: ENOENT: no such file or directory, stat '/client/build/index.html'
Run Code Online (Sandbox Code Playgroud)
所以我认为我的目录和 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}`));
Run Code Online (Sandbox Code Playgroud)
我通过在 package.json 中定义构建和安装命令解决了这个问题。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\""
},
Run Code Online (Sandbox Code Playgroud)
小智 2
我想应该是这样的
app.use("/images", express.static(path.join(__dirname, "images")));
Run Code Online (Sandbox Code Playgroud)
编辑:实际上您的应用程序期望在以下位置找到一个文件/../client/build/index.html,但该文件不存在(这就是 ENOENT 错误的含义)。因此,您要么需要创建预期的目录结构,要么配置您的应用程序,以便它在正确的目录中查找index.html。我现在明白的就是这些,希望对你有帮助。