Express.js"path必须是绝对路径或指定root到res.sendFile"错误

sal*_*lep 5 node.js express

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

我正在尝试渲染html文件(Angular),但我遇到了问题.这有效.

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

但是我不想一遍又一遍地复制和粘贴dirname,所以我尝试了这个,以免与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
 });
Run Code Online (Sandbox Code Playgroud)

这是错误.

我的快递版是4.13

path必须是绝对的或指定root到res.sendFile

Hir*_* S. 13

如果你查看sendFile的快速代码,它会检查这个条件:

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

因此,您必须通过提供root密钥传递绝对路径或相对路径.

res.sendFile('test2.html', { root: '/home/xyz/code/'});
Run Code Online (Sandbox Code Playgroud)

如果你想使用相对路径然后你可以使用path.resolve它来使它成为绝对路径.

var path = require('path');
res.sendFile(path.resolve('test2.html'));
Run Code Online (Sandbox Code Playgroud)


ras*_*had 5

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

除非在options对象中设置了root选项,否则path必须是文件的绝对路径.

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

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

之后,您可以轻松地使用此类中间件

app.use(sendViewMiddleware);

app.get('/randomlink', function(req, res) {
    res.sendView('test2.html');
});
Run Code Online (Sandbox Code Playgroud)