如果我做一个
res.sendfile('public/index1.html');
然后我得到一个服务器控制台警告
express deprecated
res.sendfile
: Useres.sendFile
instead
但它在客户端工作良好。
但是当我改变它
res.sendFile('public/index1.html');
TypeError: path must be absolute or specify root to
res.sendFile
并且不渲染index1.html。
我无法弄清楚绝对路径是什么。我有公共目录在同一级别server.js。我正在做的res.sendFile从与server.js。我也声明了app.use(express.static(path.join(__ dirname,’public’)));
添加我的目录结构:
/Users/sj/test/ ....app/ ........models/ ....public/ ........index1.html
这里要指定的绝对路径是什么?
我使用Express 4.x.
解决方法
express.static中间件与res.sendFile分离,因此使用公共目录的绝对路径初始化它将不会对res.sendFile执行任何操作。您需要使用res.sendFile直接使用绝对路径。有两种简单的方法:
> res.sendFile(path.join(__ dirname,’../public’,’index1.html’));
> res.sendFile(‘index1.html’,{root:path.join(__ dirname,’../public’)});
注意:__dirname返回当前执行的脚本所在的目录。在你的case中,看起来server.js在app /中。所以,要公开,你需要先退一级:../public/index1.html。
注意:path
is a built-in module需要为上述代码工作:var path = require(‘path’);