res.sendFile绝对路径

Kay*_*ast 121 path node.js express

如果我做了

res.sendfile('public/index1.html'); 
Run Code Online (Sandbox Code Playgroud)

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

不推荐使用res.sendfile:res.sendFile改为使用

但它在客户端工作正常.

但是当我改变它

res.sendFile('public/index1.html');
Run Code Online (Sandbox Code Playgroud)

我收到一个错误

TypeError:path必须是绝对路径或指定root到 res.sendFile

并且index1.html没有呈现.

我无法弄清楚绝对路径是什么.我的public目录与...相同server.js.我做了res.sendFileserver.js.我也宣布了app.use(express.static(path.join(__dirname, 'public')));

添加我的目录结构:

/Users/sj/test/
....app/
........models/
....public/
........index1.html
Run Code Online (Sandbox Code Playgroud)

这里指定的绝对路径是什么?

我正在使用Express 4.x.

Mik*_*e S 286

express.static中间件是独立的res.sendFile,所以用你的绝对路径初始化它public目录不会做任何事情res.sendFile.您需要直接使用绝对路径res.sendFile.有两种简单的方法可以做到:

  1. res.sendFile(path.join(__dirname, '../public', 'index1.html'));
  2. res.sendFile('index1.html', { root: path.join(__dirname, '../public') });

注意: __dirname返回当前正在执行的脚本所在的目录.在您的情况下,它看起来像是server.jsapp/.所以,为了达到这个目的public,你需要首先退出一个级别:../public/index1.html.

注意: path是一个内置模块,需要required才能使上述代码工作:var path = require('path');

  • `res.sendFile('../ public/index.html',{root:__dirname});`也可以,它更短 (12认同)
  • res.sendFile('../ public / index.html',{root:__dirname});不再起作用了,由于返回到根目录之上,因此返回403 Forbidden。做`res.sendFile('public / index.html',{root:path.dirname(__ dirname)});`。 (2认同)

Ksh*_*ary 42

试试这个:

res.sendFile('public/index1.html' , { root : __dirname});
Run Code Online (Sandbox Code Playgroud)

这对我有用.root:__ dirname将获取server.js在上例中的地址,然后转到index1.html(在这种情况下)返回的路径是到达公共文件夹所在的目录.


小智 8

res.sendFile( __dirname + "/public/" + "index1.html" );
Run Code Online (Sandbox Code Playgroud)

where __dirname将管理当前正在执行的脚本(server.js)所在目录的名称.

  • @TheThird我想,使用`path`使它与os无关. (3认同)

Phi*_*ins 6

尚未列出的对我有用的另一种选择是简单地使用path.resolve单独的字符串或仅使用整个路径之一:

// comma separated
app.get('/', function(req, res) {
    res.sendFile( path.resolve('src', 'app', 'index.html') );
});
Run Code Online (Sandbox Code Playgroud)

要么

// just one string with the path
app.get('/', function(req, res) {
    res.sendFile( path.resolve('src/app/index.html') );
});
Run Code Online (Sandbox Code Playgroud)

(节点v6.10.0)

创意源自/sf/answers/1021599771/


Abd*_*UMI 6

process.cwd()返回项目的绝对路径。

然后 :

res.sendFile( `${process.cwd()}/public/index1.html` );
Run Code Online (Sandbox Code Playgroud)


Jai*_*mez 6

根据其他答案,这是一个如何完成最常见要求的简单示例:

const app = express()
app.use(express.static('public')) // relative path of client-side code
app.get('*', function(req, res) {
    res.sendFile('index.html', { root: __dirname })
})
app.listen(process.env.PORT)
Run Code Online (Sandbox Code Playgroud)

这也是在每个请求上使用 index.html 响应的一种简单方法,因为我使用星号*来捕获在您的静态(公共)目录中找不到的所有文件;这是网络应用程序最常见的用例。更改为/仅返回根路径中的索引。


小智 5

我试过了,它奏效了。

app.get('/', function (req, res) {
    res.sendFile('public/index.html', { root: __dirname });
});
Run Code Online (Sandbox Code Playgroud)