node.js Express.js“路径必须是绝对的或指定root到res.sendFile”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34217044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Express.js "path must be absolute or specify root to res.sendFile" error
提问by salep
NOTE : This is NOT a duplicate question, I've already tried other answers to similar questions.
注意:这不是一个重复的问题,我已经尝试过类似问题的其他答案。
I'm trying to render html files (Angular) but I'm having an issue. This works.
我正在尝试呈现 html 文件(Angular),但我遇到了问题。这有效。
app.get('/randomlink', function(req, res) {
res.sendFile( __dirname + "/views/" + "test2.html" );
});
But I don't want to copy and paste dirname thingy over and over, so I tried this in order to not to be repetitive with urls:
但我不想一遍又一遍地复制和粘贴 dirname thingy,所以我尝试了这个,以免与 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
});
Here's the error.
这是错误。
My express version is 4.13
我的快递版本是 4.13
path must be absolute or specify root to res.sendFile
路径必须是绝对路径或指定 root 到 res.sendFile
回答by Hiren S.
If you look into the express code for sendFile, then it checks for this condition:
如果您查看 sendFile 的 express 代码,它会检查以下情况:
if (!opts.root && !isAbsolute(path)) {
throw new TypeError('path must be absolute or specify root to res.sendFile');
}
So You must need to pass Absolute path or relative path with providing rootkey.
所以您必须需要通过提供root密钥来传递绝对路径或相对路径。
res.sendFile('test2.html', { root: '/home/xyz/code/'});
And if you want to use relative path and then you can make use path.resolveto make it absolute path.
如果您想使用相对路径,那么您可以使用path.resolve使其成为绝对路径。
var path = require('path');
res.sendFile(path.resolve('test2.html'));
回答by Rashad Ibrahimov
You can't go against official documentation of res.sendFile()
你不能违背res.sendFile() 的官方文档
Unless the root option is set in the options object, path must be an absolute path to the file.
除非在选项对象中设置了 root 选项,否则 path 必须是文件的绝对路径。
But I understand that you don't want to copy smth like __dirnameevery time, and so for your purpose I think you can define your own middleware:
但我知道您不想__dirname每次都复制 smth ,因此为了您的目的,我认为您可以定义自己的中间件:
function sendViewMiddleware(req, res, next) {
res.sendView = function(view) {
return res.sendFile(__dirname + "/views/" + view);
}
next();
}
After that you can easily use this middleware like this
之后你可以像这样轻松地使用这个中间件
app.use(sendViewMiddleware);
app.get('/randomlink', function(req, res) {
res.sendView('test2.html');
});
回答by A-Sharabiani
Easiest way is to specify the root:
最简单的方法是指定根:
res.sendFile('index.html', { root: __dirname });

