【问题标题】:Node.js - res.sendFile - Error: ENOENT but the path is correctNode.js - res.sendFile - 错误:ENOENT 但路径正确
【发布时间】:2017-04-15 02:43:51
【问题描述】:

我正在尝试渲染 index.html,但我得到错误 enoent,即使路径正确。

//folders tree
test/server.js
test/app/routes.js
test/public/views/index.html

//routes.js    
app.get('*', function(req, res) {
    res.sendFile('views/index.html');
});


//server.js
app.use(express.static(__dirname + '/public'));
require('./app/routes')(app);

我也试过

res.sendFile(__dirname + '/public/views/index.html');

如果我使用

res.sendfile('./public/views/index.html');

然后它可以工作,但我看到一条警告说 sendfile 已弃用,我必须使用 sendFile。

【问题讨论】:

  • 当您将console.log 放入sendFile 的路径时会发生什么?你得到你期望的路径了吗?
  • 它给了我路径'/Users/me/Desktop/test/app/public/views/index.html',它应该是正确的路径
  • 你试过res.sendFile('/views/index.html');吗?
  • with res.sendFile('/views/index.html');我得到错误:ENOENT: no such file or directory, stat '/views/index.html' at Error (native)
  • 实际上,如果您只是提供静态文件,则预期的事情是根本没有定义路由,这就是静态中间件的作用。

标签: node.js express sendfile


【解决方案1】:

问题是您已经定义了静态文件中间件,但是您在它前面定义了一个尝试处理提供静态文件的路由(因此静态文件中间件实际上在这里什么都不做)。因此,如果您想从路线中res.sendFile 某些东西,您需要给它一个绝对路径。或者,您可以删除 app.get('*', ...) 路由并让 express 中间件完成其工作。

【讨论】:

  • res.sendFile 始终采用绝对路径,根据 API 文档:“除非在选项对象中设置了 root 选项,否则路径必须是文件的绝对路径。”
  • 好的,我会更正答案,但我的主要观点是,首先不需要res.sendFile。应该删除路由,以便定义的中间件可以完成其工作。
  • 是的,同意
【解决方案2】:

你可以试试下面的代码

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public/views')));

处理 api 调用

app.use('/', function(req, res, next) {
    console.log('req is -> %s', req.url);
    if (req.url == '/dashboard') {
        console.log('redirecting to  -> %s', req.url);
        res.render('dashboard');
    } else {
        res.render('index');
    }

});

【讨论】:

    【解决方案3】:

    尝试添加:

     var path = require('path');
     var filePath = "./public/views/index.html"
     var resolvedPath = path.resolve(filePath);
     console.log(resolvedPath);
     return res.sendFile(resolvedPath);
    

    这应该清楚文件路径是否是你所期望的

    【讨论】:

    • 这个有效,我现在看到路径不正确,它正在文件夹应用程序中寻找文件夹视图,而不是公共文件夹。感谢大家的帮助;)
    【解决方案4】:

    尝试使用 root 选项,这对我有用:

    var options = {
        root: __dirname + '/public/views/',
    };
    
    res.sendFile('index.html', options, function (err) {
        if (err) {
          console.log(err);
          res.status(err.status).end();
        }
        else {
          console.log('Sent:', fileName);
        }
      });
    

    【讨论】:

    • { 错误:ENOENT:没有这样的文件或目录,在错误(本机)错误时统计“/Users/me/Desktop/test/app/public/views/index.html”:-2,代码:'ENOENT',系统调用:'stat',路径:'/Users/me/Desktop/test/app/public/views/index.html',暴露:false,statusCode:404,状态:404 }
    • 那里有文件吗?
    猜你喜欢
    • 2015-11-24
    • 2018-02-04
    • 2014-10-17
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    相关资源
    最近更新 更多