注意:这不是一个重复的问题,我已经尝试过类似问题的其他答案.
我正在尝试渲染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'); });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。