【问题标题】:Unable to construct the right absolute path using path module无法使用路径模块构造正确的绝对路径
【发布时间】:2021-03-30 18:03:10
【问题描述】:

我的 MERN 应用的文件夹结构如下:

如您所见,在hamburger 目录中,有两个目录:clientserver

index.js 内部,即server 目录内部,我正在构造一个index.html 的绝对路径,它位于client\build 目录内部。请参阅下面突出显示的部分:

hamburger/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 目录内。

【问题讨论】:

    标签: node.js path mern


    【解决方案1】:

    您必须添加 ../ 以将 1 个目录向上移动到您的客户端文件夹所在的位置以构建正确的路径。

    path.resolve(__dirname, "../client", "build", "index.html")
    

    使用path.join

    path.join(__dirname, '../', 'client', 'build', 'index.html')
    

    path.join(__dirname, '../client', 'build', 'index.html')
    

    path.join(__dirname, '../client/build/index.html')
    

    【讨论】:

    • 没有一个解决方案有效。我想我将不得不更改文件夹结构。
    • @HKS 你有没有尝试console.log你得到了什么路径?
    • 再试一次。 path.resolve(__dirname, "../client", "build", "index.html") 工作。谢谢。
    【解决方案2】:

    由于您的index.js 位于server 文件夹中,因此绝对路径将始终类似于server\client\build\index.html

    要解决您的问题,您必须更改文件夹结构或手动构建路径。

    【讨论】:

      猜你喜欢
      • 2013-06-30
      • 2012-11-23
      • 1970-01-01
      • 2017-05-09
      • 2018-06-11
      • 2014-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多