node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]
The error is pretty clear, you need to specify an absolute (instead of relative) path and/or set root
in the config object for res.sendFile()
. Examples:
// assuming index.html is in the same directory as this script
res.sendFile(__dirname + '/index.html');
or specify a root (which is used as the base path for the first argument to res.sendFile()
:
res.sendFile('index.html', { root: __dirname });
Specifying the root
path is more useful when you're passing a user-generated file path which could potentially contain malformed/malicious parts like ..
(e.g. ../../../../../../etc/passwd
). Setting the root
path prevents such malicious paths from being used to access files outside of that base path.
Try adding root path.
app.get('/', function(req, res) {
res.sendFile('index.html', { root: __dirname });
});
in .mjs files we for now don't have __dirname
hence
res.sendFile('index.html', { root: '.' })