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

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

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

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

但是我不想一遍又一遍地复制和粘贴dirname,所以我尝试了这个,以免与url重复:

app.use(express.static(path.join(__dirname,'public')));
app.use(express.static(path.join(__dirname,'views')));

app.get('/randomlink',res) {
     res.sendFile('test2.html'); // test2.html exists in the views folder
 });

这是错误.

我的快递版是4.13

path must be absolute or specify root to res.sendFile

解决方法

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

Unless the root option is set in the options object,path must be an absolute path to the file.

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

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

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

app.use(sendViewMiddleware);

app.get('/randomlink',res) {
    res.sendView('test2.html');
});

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...