小编典典

res.sendFile绝对路径

node.js

如果我做一个

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

然后我收到服务器控制台警告

表达已弃用res.sendfileres.sendFile改为使用

但它在客户端工作正常。

但是当我将其更改为

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

我得到一个错误

TypeError:路径必须是绝对路径或将根目录指定为 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

在此处指定的绝对路径是什么?

我正在使用Express4.x。


阅读 526

收藏
2020-07-07

共1个答案

小编典典

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.js在中app/。因此,要进入public,您首先需要退出一个级别:../public/index1.html

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

2020-07-07