我的目录设置如下:
public
pages
index.html
routers
route.js
在route.js中,我执行以下操作:
router.get('/', function(req, res) {
res.sendFile("/public/pages/index.html", {"root": __dirname});
});
我错误:ENOENT:没有此类文件或目录,stat ,因为服务器正在查看myproject/routers/public/pages/index.html
而不是myproject/public/pages/index.html
1)如何解决此问题并使用_dirname
查看正确的路径?
2)如何让我的服务器记住/public/pages/
,这样我就不会每次必须指定绝对路径?
答案 0 :(得分:1)
所以你可能想要使用相对位置,对于你的例子你可以做类似下面的事情
var html_location = './public/pages/'; //first method
var root_location = { //second method
root : './public/pages/'
}
router.get('/', function(req, res) {
res.sendFile('index.html', { root : html_location}); //first method
res.sendFile('index.html', root_location); //second method
});
所以根:'。'表示您将从运行main.js / app.js文件的文件夹中启动该位置,并且文件位置已从该位置关闭。