node.js - How does Express/Connect middleware work? -
i learning node.js, , have read tutorials, node beginner book learning core funcionality. more read examples, more doubts start collecting.
on further example, obtained tutorial, can see crud 'read' request key /documents/titles.json, returning value:
app.get('/documents/titles.json', loaduser, function(req, res) { document.find({ user_id: req.currentuser.id },[], { sort: ['title', 'descending'] }, function(err, documents) { res.send(documents.map(function(d) { return { title: d.title, id: d._id }; })); }); }); on example, function loaduser() used authentication purposes:
function loaduser(req, res, next) { if (req.session.user_id) { user.findbyid(req.session.user_id, function(err, user) { if (user) { req.currentuser = user; next(); } else { res.redirect('/sessions/new'); } }); } } what don't understand is:
- i suppose node.js, before start executing app.get, goes loaduser function.
loaduser()function has 3 parameters: req,res,next, don't see, @ least, how passapp.get()"req" parameterloaduser(). come? - inside
loaduser()function, when executenext(), means functionapp.get()" can continue procedure, req.currentuser = user, same req used onapp.get()function? - inside
loaduser()function, when executeres.redirect()code, automatically breaks procedure onapp.get()function, right? looks doesn't returndocument.find().
the questions you've asked express framework internals specifically:
when call app.get(route, loaduser, final) express make stack (array) loaduser , final function functions , know when call next should execute following function in stack same req , res params.
when call next pass next function in middleware stack.
since call res.redirect , don't call return, won't pass next function in stack (the 1 document.find).
resources:
Comments
Post a Comment