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:

  1. 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 pass app.get() "req" parameter loaduser(). come?
  2. inside loaduser() function, when execute next(), means function app.get()" can continue procedure, req.currentuser = user, same req used on app.get() function?
  3. inside loaduser() function, when execute res.redirect() code, automatically breaks procedure on app.get() function, right? looks doesn't return document.find().

the questions you've asked express framework internals specifically:

  1. 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.

  2. when call next pass next function in middleware stack.

  3. since call res.redirect , don't call return, won't pass next function in stack (the 1 document.find).

resources:

http://howtonode.org/getting-started-with-express


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -