gpt4 book ai didi

node.js - Express.js "path must be absolute or specify root to res.sendFile"错误

转载 作者:搜寻专家 更新时间:2023-10-31 22:36:19 24 4
gpt4 key购买 nike

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

我正在尝试呈现 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', function(req, res) {
res.sendFile('test2.html'); // test2.html exists in the views folder
});

这是错误。

我的express版本是4.13

path must be absolute or specify root to res.sendFile

最佳答案

如果您查看 sendFile 的快速代码,它会检查以下条件:

if (!opts.root && !isAbsolute(path)) {
throw new TypeError('path must be absolute or specify root to res.sendFile');
}

因此,您必须需要通过提供 root key 来传递绝对路径或相对路径。

res.sendFile('test2.html', { root: '/home/xyz/code/'});

如果你想使用相对路径,那么你可以使用 path.resolve 使其成为绝对路径。

var path = require('path');
res.sendFile(path.resolve('test2.html'));

关于node.js - Express.js "path must be absolute or specify root to res.sendFile"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34217044/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com