如何解决无法使用路径模块
我的 MERN 应用的文件夹结构如下:
如您所见,在 hamburger
目录中,有两个目录:client
和 server
。
在位于 index.js
目录内的 server
内,我正在构造一个到 index.html
的绝对路径,它位于 client\build
目录内。请参阅下面突出显示的部分:
汉堡包/server/index.js
const express = require("express");
const path = require("path");
const dotenv = require("dotenv");
const colors = require("colors");
const connectDB = require("./config/db");
const {
notFound,globalErrorHandler,} = require("./middleware/errorMiddleware");
const userRoutes = require("./routes/userRoutes");
const downloadRoutes = require("./routes/downloadRoutes");
dotenv.config();
connectDB();
const app = express();
app.use(express.json());
app.use("/api/users",userRoutes);
app.use("/api/download",downloadRoutes);
// Routing logic in production
if (process.env.NODE_ENV === "production") {
app.use(express.static(path.join(__dirname,"../client/build")));
app.get("*",(req,res) => {
res.sendFile(path.resolve(__dirname,"client","build","index.html"));
});
}
app.use(notFound);
app.use(globalErrorHandler);
const PORT = process.env.PORT || 5000;
app.listen(PORT,() => {
console.log(`Server listening on port ${PORT}`.yellow.bold);
});
问题
目前绝对路径解析为server\client\build\index.html
,这是错误的,因为client
目录不在server
目录内;它位于 hamburger
目录中。
我想要什么?
我需要在 path.resolve()
内进行哪些更改,以便获得 index.html
的正确绝对路径,该路径位于 client\build
目录中。
解决方法
由于您的 index.js
位于 server
文件夹中,因此绝对路径将始终类似于 server\client\build\index.html
。
要解决您的问题,您必须更改文件夹结构或手动构建路径。
,您必须添加 ../
才能将客户端文件夹所在的目录向上移动 1 个目录以构建正确的路径。
path.resolve(__dirname,"../client","build","index.html")
path.join(__dirname,'../','client','build','index.html')
或
path.join(__dirname,'../client','../client/build/index.html')
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。