express js error : “express deprecated res.sendfile: Use res.sendFile instead”

express js error : “express deprecated res.sendfile: Use res.sendFile instead”

我有这个代码:

app.get('/', function(req, res) {
        res.sendfile('public/index.html');
}); 

app.use("/public", express.static(__dirname + '/public'));

这是给我的错误:

express deprecated res.sendfile: Use res.sendFile instead

因此,正如此类似主题 (express js error : "express deprecated res.sendfile: Use res.sendFile instead") 中所建议的,我尝试将 sendfile 重命名为 sendFile,但它给了我另一个错误:

TypeError: path must be absolute or specify root to res.sendFile
at ServerResponse.sendFile (/Users/nacho4d/dev-enquete/node_modules/express/lib/response.js:394:11)
at /Users/nacho4d/dev-enquete/app.js:37:6

我应该在这里做什么?我不确定是否应该传递绝对路径(因为下一行: app.use("/public", ... 。 我不太明白的意思也把根指定给res.sendFile

感谢任何帮助。

What should I do here? I am not sure if I should pass an absolute path (because of the next line: app.use("/public", ... .

我不能说对express很熟悉,但是我怀疑你要传给sendFile的路径和路由有什么关系。您很可能只需要将绝对路径传递给文件系统中的文件。

I don't know understand well the meaning of specify the root to res.sendFile too.

如果您查看 documentation,您会发现 sendFile 接受一个选项对象作为第二个参数。 root 是选项之一:

root: Root directory for relative filenames.

它还有一个示例说明如何使用选项(包括 root)。

如果你传递一个相对文件路径,express似乎不知道从哪里开始寻找文件(文件所在的目录?服务器启动的目录?),因此它需要你告诉它。