【问题标题】:Node.js + Express: What do I have to serve the specific folder's path to express.static?Node.js + Express:我必须为 express.static 提供特定文件夹的路径吗?
【发布时间】:2017-08-31 04:13:04
【问题描述】:

我写了以下代码:

var express = require('express');
var app = express();

app.use('/', express.static(__dirname ));

app.get('/', function (req, res) {
  res.sendFile('./dist/index.html');
});


app.listen(3000, function() {
  console.log("Listening on port 3000");
});

这是行不通的。打开浏览器并转到“localhost:3000”时出现错误:

路径必须是绝对路径或指定 res.sendFile 的根目录

当然,一旦我将“app.use ...”开头的行修复为:

app.use('/', express.static(__dirname + "./dist"));

然后一切正常。

你能解释一下原因吗?给“express.static”一个发送文件的直接文件夹的父文件夹路径有什么问题?

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    尝试更改顺序。而不是:

    app.use('/', express.static(__dirname ));
    
    app.get('/', function (req, res) {
      res.sendFile('./dist/index.html');
    });
    

    试试:

    app.get('/', function (req, res) {
      res.sendFile(path.join(__dirname, './dist/index.html'));
    });
    
    app.use('/', express.static(__dirname));
    // OR:
    app.use('/', express.static(path.join(__dirname, 'dist')));
    

    另外使用path.join() 加入路径。你需要先要求path

    var path = require('path');
    

    有关提供静态文件以及为什么path.join 很重要的更多信息,请参阅此答案:

    现在,您的问题不在于express.static,而在于res.sendFile。当您将express.static 路径更改为不同的路径时,您之前要使用res.sendFile 发送的文件可能已被express.static 找到,而带有res.sendFile 的处理程序根本没有运行。在更改之前,express.static 没有找到 index.html 文件,并且正在将请求传递给下一个处理程序——它有一个错误的 res.sendFile 调用。这就是为什么它似乎解决了错误的问题,因为不再调用导致错误的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-15
      • 2020-06-28
      • 1970-01-01
      • 2014-09-14
      • 1970-01-01
      • 2022-07-16
      • 2016-12-11
      • 2017-07-30
      相关资源
      最近更新 更多