res.sendFile绝对路径 [英] res.sendFile absolute path
问题描述
如果我执行
res.sendfile('public / index1.html');
然后我得到一个服务器控制台警告
express deprecated
res.sendfile
:使用res.sendFile
替代
但它在客户端工作正常。
但是当我将其更改为
res.sendFile('public / index1.html');
我收到错误
TypeError:path必须是绝对值,或指定root到
res.sendFile
和 index1.html
不呈现。
我无法弄清楚绝对路径是。与 server.js
相同级别的 public
目录。我正在使用 server.js
执行 res.sendFile
。我也声明了 app.use(express.static(path.join(__ dirname,'public')));
添加我的目录结构
/ Users / sj / test /
/ pre>
.... app /
........ models /
.... public /
........ index1.html
这里要指定的绝对路径是什么?
我正在使用Express 4.x。
解决方案
express.static
中间件与res.sendFile
分开,因此使用绝对路径初始化为public
目录不会对res.sendFile
执行任何操作。您需要直接用res.sendFile
使用绝对路径。有两种简单的方法:
res.sendFile(path.join(__ dirname,'.. / public','index1.html'));
res.sendFile('index1.html',{root:path .join(__ dirname,'../public')});
注意:
__ dirname
返回当前执行脚本所在的目录。在这种情况下,它看起来像server.js
在
app /
中。因此,要获得public
,您需要先退出一级:../ public / index1.html
。
注意:
路径
是一个内置模块,需要require
d代表上述代码工作:var path = require('path');
If I do a
res.sendfile('public/index1.html');
then I get a server console warning
express deprecated
res.sendfile
: Useres.sendFile
insteadbut it works fine on the client side.
But when I change it to
res.sendFile('public/index1.html');
I get an error
TypeError: path must be absolute or specify root to
res.sendFile
and
index1.html
is not rendered.I am unable to figure out what the absolute path is. I have
public
directory at the same level asserver.js
. I am doing theres.sendFile
from withserver.js
. I have also declaredapp.use(express.static(path.join(__dirname, 'public')));
Adding my directory structure:
/Users/sj/test/ ....app/ ........models/ ....public/ ........index1.html
What is the absolute path to be specified here ?
I'm using Express 4.x.
解决方案The
express.static
middleware is separate fromres.sendFile
, so initializing it with an absolute path to yourpublic
directory won't do anything tores.sendFile
. You need to use an absolute path directly withres.sendFile
. There are two simple ways to do it:
res.sendFile(path.join(__dirname, '../public', 'index1.html'));
res.sendFile('index1.html', { root: path.join(__dirname, '../public') });
Note:
__dirname
returns the directory that the currently executing script is in. In your case, it looks likeserver.js
is inapp/
. So, to get topublic
, you'll need back out one level first:../public/index1.html
.Note:
path
is a built-in module that needs to berequire
d for the above code to work:var path = require('path');
这篇关于res.sendFile绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!