res.sendFile绝对路径
如果我做了
res.sendfile('public/index1.html');
然后,我得到了一个服务器控制台警告
表示不赞成使用
res.sendfile
:使用res.sendFile
代替
但它工作在客户端的罚款。
但是,当我将其更改为
res.sendFile('public/index1.html');
我得到一个错误
类型错误:路径必须是绝对的或指定根
res.sendFile
而index1.html
不会被渲染。
我无法弄清楚的绝对路径是什么。我在同一水平public
server.js
目录。我从res.sendFile
做server.js
。我也宣布app.use(express.static(path.join(__dirname, 'public')));
加入我的目录结构:
/Users/sj/test/
....app/
........models/
....public/
........index1.html
什么是在这里指定的绝对路径?
我用快递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
。
注:path
is a built-in module需要被require
d上面的代码工作:var path = require('path');
res.sendFile绝对路径
如果我做了
res.sendfile('public/index1.html');
然后,我得到了一个服务器控制台警告
表示不赞成使用
res.sendfile
:使用res.sendFile
代替
但它工作在客户端的罚款。
但是,当我将其更改为
res.sendFile('public/index1.html');
我得到一个错误
类型错误:路径必须是绝对的或指定根
res.sendFile
而index1.html
不会被渲染。
我无法弄清楚的绝对路径是什么。我在同一水平public
server.js
目录。我从res.sendFile
做server.js
。我也宣布app.use(express.static(path.join(__dirname, 'public')));
加入我的目录结构:
/Users/sj/test/
....app/
........models/
....public/
........index1.html
什么是在这里指定的绝对路径?
我用快递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
。
注:path
is a built-in module需要被require
d上面的代码工作:var path = require('path');