2013-04-22 124 views
1

Node noob here。 :)我在做一個Ajax請求的代碼node.js + express:`sendfile`給Ajax請求給出404

var path = "/path/to/file.html"; 

$.get(path, function(data) { 
    $("#post").html(data); 
}); 

,並在服務器端,有

app.use(express.directory(__dirname + '/public')); 

app.get('/path/*', function(req, res) { 
    var is_ajax_request = req.xhr; 
    if(is_ajax_request) 
     res.sendfile(req.path); 
    else 
     res.sendfile('public/index.html'); 
}); 

在實際文件位於public/path/to/file.html響應。由於某種原因,阿賈克斯給我的錯誤

GET http://localhost:3000/path/to/file.html 404 (Not Found) 

即使路徑是肯定的是正確的。事實上,如果我刪除整個app.get函數,它會發現文件沒有問題。有沒有另外一種方法可以迴應Ajax請求?

+0

我認爲你在這裏有道路混亂。您在執行'sendFile'之前是否嘗試過'console.log'路徑?這應該很快證實它不僅僅如此簡單。 – 2013-04-22 07:39:05

+0

Doh!我不得不使用'res.sendfile('public /'+ req.path)',因爲當使用'sendfile()'時,路徑必須與'app.js'相關。令我困惑的是,錯誤消息顯示了一條看起來正確的路徑。謝謝。 – apostl3pol 2013-04-22 07:45:00

+0

添加如下,以便您可以「標記爲已回答」爲未來世代:) – 2013-04-22 07:59:07

回答

1

我覺得你在這裏路徑混亂。

您是否嘗試過console.log路徑,然後再執行sendFile?這應該很快證實它不僅僅如此簡單。

看起來你需要使用res.sendfile('public/' + req.path)