Node noob here. :) I'm making an Ajax request with the code
var path = "/path/to/file.html";
$.get(path, function(data) {
$("#post").html(data);
});
and on the server side, responding with
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');
});
where the actual file is located at public/path/to/file.html. For some reason Ajax is giving me the error
GET http://localhost:3000/path/to/file.html 404 (Not Found)
even though the path is correct for sure. In fact, if I remove the whole app.get function it finds the file no problem. Is there another way I should respond to the Ajax requests?
I think you have path confusion here.
Did you try to console.log the paths before you do the sendFile? That should quickly confirm it's not just that simple.
Looks like you need to use res.sendfile('public/' + req.path).
Try this:
res.sendfile(__dirname + '/public/index.html');
You can also refer NodeJS: Render raw HTML with Express and Render basic HTML view in Node JS Express?