Express.js报错TypeError: path must be absolute or specify root to res.sendFile
解决 res.sendFile 报错:TypeError: path must be absolute or specify root to res.sendFile
这个错误我之前在Express项目里也踩过坑,其实原因特别直白——res.sendFile() 要求你传入的文件路径要么是绝对路径,要么通过 root 参数明确告诉它文件所在的根目录,不然Express根本没法定位到你要找的index.html到底在哪。
给你几个实用的解决办法:
方法1:用 __dirname 拼接绝对路径
__dirname 是Node.js自带的内置变量,代表当前代码文件所在目录的绝对路径,用它和文件名拼接就能得到完整的绝对路径:
app.get('/', function(req, res) { res.sendFile(__dirname + '/index.html'); });
要是想更规范(避免不同操作系统路径分隔符的差异问题),可以用Node.js的path模块来拼接路径:
const path = require('path'); // 记得先引入path模块 app.get('/', function(req, res) { res.sendFile(path.join(__dirname, 'index.html')); });
方法2:指定 root 参数
如果你不想写长长的绝对路径,也可以通过root参数告诉Express文件所在的根目录,这样直接用相对路径就行:
app.get('/', function(req, res) { res.sendFile('index.html', { root: __dirname }); });
这两种方法都能完美解决这个报错,选哪种全看你个人习惯~
内容的提问来源于stack exchange,提问作者Mehadi Hassan
相关产品推荐
相关产品推荐

