Node.js - res.sendFile - Error: ENOENT but the path is correct

Node.js - res.sendFile - Error: ENOENT but the path is correct

我正在尝试渲染一个 index.html 但我得到了错误提示,即使路径正确。

//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。

尝试使用 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);
    }
  });

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

尝试添加:

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

这应该可以弄清文件路径是否符合您的预期

你可以试试下面的代码

// 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');
    }

});