node.js - ajax request gives a 404 with express server (chrome) loads successfully with firefox without a server? -
i'm trying issue ajax request index view . .
├── app.js | ├── package.json ├── ajax │ ├──ajax.txt | ├── home.ejs
- server renders 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 server . - making express server give 404
get http://localhost:3000/ajax/ajax.txt 404 (not found)
- home simple issues request when button 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);
from express code show, there no route handler responds request http://localhost:3000/ajax/ajax.txt
.
an express web server not serve files default. so, serves files have created explicit route handler or have configured sort of middleware serve 1 or more static files in automatic fashion. so, unlike other web servers, express not in server file system matching file send requesting client. if there's no route or middleware explicitly designed handle particular request, 404.
you can use app.use(express.static(...))
configure static file handling express. example, can configure automatically serve whole directory of static , public files. example, used serve .css , .js files static files.
for example, simple express route handle /ajax/ajax.txt
request this:
app.get("/ajax/ajax.txt", function(req, res) { res.sendfile("ajax/ajax.txt"); });
depending upon else want static files, use express.static()
middleware configure 1 or more static files automatically served express server. see the doc various options , ways use it.
Comments
Post a Comment