【问题标题】:Locating parent directory using "path.join" not working on Heroku使用“path.join”定位父目录在 Heroku 上不起作用
【发布时间】:2020-05-09 23:46:07
【问题描述】:

这是我的应用程序的简要结构

  ├── client
  │     └─ build
  │          └─ index.html
  │
  │
  ├── server
  │     └─ index.js

Heroku 上的生产代码如下:

// index.js

if (process.env.NODE_ENV === "production") {

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


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

下面 Heroku 的错误:

正如错误日志所说,不知何故 path.join(__dirname, "/../client/build") 没有指向服务器目录(根)之外的客户端目录,而是只需找到相同的 server 目录,例如 /server/client 这是错误的路径,甚至不存在,如上面的错误所示。

如何定位“clinet/build/”?

【问题讨论】:

    标签: express heroku path


    【解决方案1】:

    终于想通了。

    由于构建了 TypeScript 的 dist 目录,并且 index.js 嵌套在 so 中。

    它实际上是 server/dist/index.js 而不是 server/index.js,因为它更深一层。

    因此,要到达根目录,必须是'/../../'而不是'/../'

    下面的工作代码:

    if (process.env.NODE_ENV === "production") {
    
      app.use(express.static(path.join(__dirname, "/../../client/build")));
    
      app.get("*", (req, res) => {
        res.sendFile(path.join(__dirname, "/../../client/build", "index.html"));
      });
    }
    

    【讨论】:

      【解决方案2】:

      我理解你想要做什么,但试试这个希望它对你有用

        app.use(express.static('client/build'));
          app.get('*',(req,res)=>{
              res.sendFile(path.resolve(__dirname,'client','build','index.html'))
          })
      

      【讨论】:

        猜你喜欢
        • 2018-01-22
        • 2020-11-10
        • 1970-01-01
        • 1970-01-01
        • 2021-09-09
        • 1970-01-01
        • 2020-09-19
        • 1970-01-01
        • 2015-06-25
        相关资源
        最近更新 更多