user3260606 user3260606 - 3 months ago 25
Node.js Question

ajax request gives a 404 with express server (chrome) loads successfully with firefox without a server?

I'm trying to issue an ajax request from my index view .
.

├── app.js
|
├── package.json
├── ajax
│ ├──ajax.txt
|
├── home.ejs



  • server is just renders the home page





app.set('views' , './');
app.set('view engine' , 'ejs');
app.get('/' , function(req , res){
res.render('01');
});



-ajax script loads fine in firefox without a server .
- making an express server it give a 404

GET http://localhost:3000/ajax/ajax.txt 404 (Not Found)



  • home simple issues a request when button is clicked .





var loadAjax = document.getElementsByTagName('button')[0];
loadAjax.addEventListener('click' , function(e){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if((xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304)){
var rText = document.createTextNode(xhr.responseText);
var p = document.createElement('p');
p.appendChild(rText);
document.body.appendChild(p);
}
};
xhr.open('GET' , 'ajax/ajax.txt' , true);
xhr.send(null);


Answer

From the Express code you show, there is no route handler that responds to a request for http://localhost:3000/ajax/ajax.txt.

An express web server does not serve any files by default. So, it only serves files that you have created an explicit route handler for or you have configured some sort of middleware to serve one or more static files in an automatic fashion. So, unlike some other web servers, Express does not just look in your server file system for a matching file to send back to the requesting client. If there's no route or middleware explicitly designed to handle that particular request, you get a 404.

You can use app.use(express.static(...)) to configure some static file handling for Express. For example, you can configure it to automatically serve a whole directory of static and public files. For example, this is often used to serve .css and .js files which are usually static files.

For example, a simple Express route to handle just your /ajax/ajax.txt request would look like this:

app.get("/ajax/ajax.txt", function(req, res) {
    res.sendFile("ajax/ajax.txt");
});

Depending upon what else you want to do with static files, you could also use express.static() middleware to configure one or more static files to be automatically served by your Express server. See the doc for the various options and ways to use it.