简体   繁体   English

dirname与提供sendFile()Node.js的根路径

[英]dirname vs. providing root path for sendFile() Node.js

I'm following a tutorial on the MEAN stack, but it's a bit old and some of the methods the author uses are deprecated. 我正在关注MEAN堆栈上的教程,但是它有点旧,并且作者使用的某些方法已被弃用。 He uses sendfile() and I changed it to sendFile() because the server was giving me warnings about sendfile() being deprecated. 他使用sendfile(),我将其更改为sendFile(),因为服务器向我发出了有关不建议使用sendfile()的警告。 The new sendFile() says it takes an absolute path as opposed to a relative one. 新的sendFile()表示,它采用的是绝对路径,而不是相对路径。 I had an endpoint which worked: 我有一个工作的端点:

app.get('/', function (req, res){
    res.sendFile(__dirname + 'layouts/posts.html')
})

in the server, but now we're breaking all the endpoints out into controllers. 在服务器中,但是现在我们将所有端点分解为控制器。 The current (relevant) file structure looks like this: 当前(相关)文件结构如下所示:

/controllers/static.js /controllers/static.js

/layouts/posts.html /layouts/posts.html

The tutorial says the endpoint in /controllers is supposed to look like this: 本教程说/ controllers中的端点应该看起来像这样:

var router = require('express').Router()

router.get('/', function (req, res){
    res.sendFile('layouts/posts.html')
})

module.exports = router

with this corresponding code in the server: 服务器中的以下相应代码:

app.use(require('./controllers/static'))

With ('layouts/post.html') I get the error "path must be absolute or specify root to res.sendFile" and when I try to add __dirname or a path from the server root, I get an ENOENT ...../controllers/somethingItried/posts.html. 使用('layouts / post.html')时出现错误“路径必须是绝对路径或将根目录指定为res.sendFile”,当我尝试从服务器根目录添加__dirname或路径时,我得到了ENOENT...。 ./controllers/somethingItried/posts.html。 Can someone explain the best way to fix this and what the server is considering the absolute path here? 有人可以解释解决此问题的最佳方法,以及服务器在此处考虑的绝对路径吗? My attempts to make a path from root have failed: 我尝试从根目录建立路径失败:

../layouts/posts.html ../layouts/posts.html

as well as the suggestions from this page: 以及此页面上的建议:

node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON] node.js TypeError:路径必须是绝对路径或为res.sendFile指定根目录[无法解析JSON]

将根路径添加到下一个参数“选项”,例如:

res.sendFile('layouts/posts.html', {root: __dirname});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM