node.js + express:`sendfile`给Ajax请求给404

节点noob在这里。 :)我正在用代码发出一个Ajax请求

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 。 出于某种原因,Ajax给我的错误

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

即使path是正确的。 事实上,如果我删除了整个app.get函数,它发现文件没有问题。 有没有另外一种方法来回应Ajax请求?

我想你在这里有道路混乱。

你做sendFile之前,是否尝试过console.logpath? 这应该很快证实它不是那么简单。

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

尝试这个:

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

你也可以参考渲染原始的HTML和渲染基本的HTML视图?