Express.js "must be absolute or specify root for res.sendFile" error

NOTE. This is not a duplicate question; I have already tried other answers to similar questions.

I am trying to display html files (Angular) but I am having a problem. It works.

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

But I don’t want to copy and paste the dirname thingy again and again, so I tried this so as not to repeat with the urls:

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

This is a mistake.

My express version 4.13

the path must be absolute or specify root for res.sendFile

+4
source share
2 answers

You cannot go against the official res.sendFile () documentation

If the root parameter is not specified in the options object, the path must be an absolute path to the file.

, smth, __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');
});
+5

- sendFile, :

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'));
+10

Source: https://habr.com/ru/post/1619444/


All Articles