You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:04:05