NodeJS 获取TypeError:path必须是绝对路径或在Expressjs中指定res.sendFile的root

vptzau2j  于 2023-08-04  发布在  Node.js
关注(0)|答案(3)|浏览(71)

下面是我的代码:

app.get('/',function(req,res){
res.sendFile('index.html');
});

字符串
获取以下错误:-

TypeError: path must be absolute or specify root to res.sendFile
at ServerResponse.sendFile

u4dcyp6a

u4dcyp6a1#

http://expressjs.com/en/4x/api.html#res.sendFile您需要指定“index.html”的完整路径,或者执行类似var options = {'root':<your_root_directory>}; res.sendFile('index.html',options);的操作

2mbi3lxu

2mbi3lxu2#

如果要使用相对路径,则需要提供sendFile的绝对路径或指定root。

绝对路径

提供像E:\\myProj\\static\\index.html这样的绝对路径。

或者提供Root类似

res.sendFile('index.html',{ root: "E:\\myProj\\static"});

字符串

crcmnpdw

crcmnpdw3#

基于上面“需要帮助”提供的答案,我点击了www.example.com的链接https://expressjs.com/en/4x/api.html#res.sendFile,其中描述了sendFile选项。在从他们的例子中复制代码后,我了解到“path”需要导入,并且在stackOverflow的一个单独的答案中发现,在我的HTML文件的文件夹可以在相对URL中定义之前,需要构造“--dirname”。
将以下代码添加到我的index.js文件中:

// start express requires sendFile() path options to be defined 
import path from 'path'
import url from 'url'
const __filename = url.fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
let sendFileOptions = {
  // where second parameter below ('views') is the folder where files 
  // which are to be sent, are located within root of my ExpressJS app
  root: path.join(__dirname, 'views'),
  dotfiles: 'deny',
  headers: {
    'x-timestamp': Date.now(),
    'x-sent': true
  }
}
// end express sendFile() options

字符串
现在在我的Express.js请求函数中,我调用sendFileOptions如下:

app.use((req, res) => {
    res.status(404).sendFile('404.html', sendFileOptions)
})

相关问题