【问题标题】:Express.js "path must be absolute or specify root to res.sendFile" errorExpress.js“路径必须是绝对路径或指定根到 res.sendFile”错误
【发布时间】:2016-03-16 23:35:32
【问题描述】:

注意:这不是一个重复的问题,我已经尝试过类似问题的其他答案。

我正在尝试渲染 html 文件 (Angular),但我遇到了问题。 这行得通。

app.get('/randomlink', function(req, res) {
    res.sendFile( __dirname + "/views/" + "test2.html" );
});

但我不想一遍又一遍地复制和粘贴目录名,所以我尝试了这个,以免与 url 重复:

app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'views')));

app.get('/randomlink', function(req, res) {
     res.sendFile('test2.html'); // test2.html exists in the views folder
 });

这是错误。

我的 express 版本是 4.13

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

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    如果你查看 sendFile 的 express 代码,那么它会检查这个条件:

    if (!opts.root && !isAbsolute(path)) {
        throw new TypeError('path must be absolute or specify root to res.sendFile');
    }
    

    所以您必须通过提供root 键来传递绝对路径或相对路径。

    res.sendFile('test2.html', { root: '/home/xyz/code/'});
    

    如果你想使用相对路径,那么你可以使用path.resolve 使其成为绝对路径。

    var path = require('path');
    res.sendFile(path.resolve('test2.html'));
    

    【讨论】:

    • 这正是我所需要的。我不得不在带有./path 的目录中后退一步,而__dirname 并没有提供那种灵活性,或者我可能做得不对,但是路径是gorgeos!
    • 但是现在root 选项必须是绝对的!在我的情况下,节点文件位于子文件夹中,它需要提供比目录高一个目录的文件。
    【解决方案2】:

    不能违背res.sendFile()的官方文档

    除非在选项对象中设置了根选项,否则路径必须是文件的绝对路径。

    但我知道你不想每次都像__dirname一样复制,所以为了你的目的,我认为你可以定义自己的中间件:

    function sendViewMiddleware(req, res, next) {
        res.sendView = function(view) {
            return res.sendFile(__dirname + "/views/" + view);
        }
        next();
    }
    

    之后你就可以像这样轻松使用这个中间件了

    app.use(sendViewMiddleware);
    
    app.get('/randomlink', function(req, res) {
        res.sendView('test2.html');
    });
    

    【讨论】:

      【解决方案3】:

      最简单的方法是指定根:

      res.sendFile('index.html', { root: __dirname });
      

      【讨论】:

      • 但是如果__dirname 不是根呢?
      【解决方案4】:

      我遇到了同样的问题,然后我解决了我的问题如下。

      const path = require("path")
      app.get('/', (req, res)=>{
          res.sendFile(path.resolve("index.html"))
      }
      

      祝你好运

      【讨论】:

        猜你喜欢
        • 2016-09-29
        • 2015-01-14
        • 2018-02-04
        • 2018-03-18
        • 1970-01-01
        • 2014-10-17
        • 2014-02-28
        • 2022-12-15
        相关资源
        最近更新 更多