2016-11-30 111 views
0

我想呈現一個index.html,但我得到錯誤enoent,即使有正確的路徑。Node.js - res.sendFile - 錯誤:ENOENT,但路徑正確

//folders tree 
test/server.js 
test/app/routes.js 
test/public/views/index.html 

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


//server.js 
app.use(express.static(__dirname + '/public')); 
require('./app/routes')(app); 

我也試過

res.sendFile(__dirname + '/public/views/index.html'); 

如果我使用

res.sendfile('./public/views/index.html'); 

然後它的工作原理,但我看到上面寫着的sendfile已被棄用警告,我不得不使用SENDFILE。

+1

什麼時候會發生什麼你的'console.log'是你放入'sendFile'的路徑嗎?你有沒有得到你期望的道路? – Aurora0001

+0

它給了我路徑'/Users/me/Desktop/test/app/public/views/index.html',它應該是正確的路徑 – Alex

+0

然後你可以包含** complete **錯誤信息嗎?看起來很奇怪,路徑是正確的,但它仍然不起作用。 – Aurora0001

回答

2

嘗試增加:

var path = require('path'); 
var filePath = "./public/views/index.html" 
var resolvedPath = path.resolve(filePath); 
console.log(resolvedPath); 
return res.sendFile(resolvedPath); 

這應該清理的文件路徑是否是你所期望它是

+0

這一個工作,我現在看到,路徑是不正確的,它正在文件夾應用程序,而不是公共文件夾尋求文件夾視圖。感謝大家的幫助;) – Alex

0

嘗試使用root選項,這爲我做:

var options = { 
    root: __dirname + '/public/views/', 
}; 

res.sendFile('index.html', options, function (err) { 
    if (err) { 
     console.log(err); 
     res.status(err.status).end(); 
    } 
    else { 
     console.log('Sent:', fileName); 
    } 
    }); 
+0

{錯誤:ENOENT:沒有這樣的文件或目錄,stat'/用戶/我/桌面/測試/應用程序/公共/視圖/索引。 html' at Error(native) errno:-2, code:'ENOENT', syscall:'stat', path:'/Users/me/Desktop/test/app/public/views/index.html ', 公開:false, statusCode:404, status:404} – Alex

+0

有沒有文件? – xShirase

0

的問題是,你定義靜態文件的中間件,但是你前面那個試圖處理服務定義路由靜態文件(所以靜態文件中間件實際上什麼都不做)。所以如果你想要從某條路線上獲得某種東西,你需要給它一條絕對路徑。或者,您可以刪除app.get('*', ...)路由並讓快速中間件完成其工作。

+0

根據API文檔,res.sendFile始終採用絕對路徑:「除非選項對象中設置了根選項,否則路徑必須是該文件的絕對路徑。「 – xShirase

+0

好的,我會更正答案,但我的主要觀點是,首先不需要」res.sendFile「。應該刪除路由以便定義的中間件可以完成它的工作。 – Kevin

+0

yup,同意那 – xShirase

0

你可以試試下面的代碼

// view engine setup 
app.set('views', path.join(__dirname, 'views')); 
app.engine('html', require('ejs').renderFile); 
app.set('view engine', 'html'); 
app.use(express.static(path.join(__dirname, 'public/views'))); 

處理API調用

app.use('/', function(req, res, next) { 
    console.log('req is -> %s', req.url); 
    if (req.url == '/dashboard') { 
     console.log('redirecting to -> %s', req.url); 
     res.render('dashboard'); 
    } else { 
     res.render('index'); 
    } 

}); 
相關問題