node.js – res.sendFile绝对路径

如果我做一个

res.sendfile('public/index1.html');

然后我得到一个服务器控制台警告

express deprecated res.sendfile: Use res.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’);

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...