How is express req.session stored?

I am very new to learning Node and Express, and I'm still trying to wrap my head in code movement with an expression. Suppose we have code that looks like this in session.js:

app.post('/session', notLoggedIn, function(req, res) { User.findOne({ username: req.body.username, password: req.body.password }, function (err, user) { if (err) { return next(err); } if (user) { req.session.user = user; res.redirect('/users'); } else { res.redirect('/session/new'); } }); }); 

Assuming the user is a mandatory mongo scheme. What I find strange is the appointment of session.user:

 req.session.user = user; 

Since the req variable will be unavailable after the redirect, but we obviously do this to save user data, I can only figure out which of the following scripts describes what happens. Either (A) the argument that is assigned to the req parameter (when the callback is called) is stored / somewhere else on the stack, (B) the session is stored / is on the stack and assigned to the new req object before it (C) matches B, but in the user’s field (it seems unlikely and possibly far-fetched on my part).

+7
javascript session express
source share
1 answer

There is a general session data structure in which all session information is stored (for example, global, but it can also be in the database), which is constant, at least for different connections). Each client session uses one unique key for indexing in the session store to obtain session data for this client.

The session creation part for this browser client creates a unique client key (which is usually stored in a cookie), which becomes the index in the global session object.

On an incoming HTTP request, the Express middleware that supports the session checks for a specific client cookie, and if that particular cookie is found in the HTTP request and found in the global object / session database, it adds that the session stores information in the request object for the http request handler for later use.

So here is a typical sequence:

  • Incoming HTTP request.
  • The verification tool checks for a session cookie.
  • If the session cookie does not exist, then create it and in the process create a unique identifier to identify this http client.
  • In the persistent session store, initialize the session for this new client.
  • If a session cookie exists, go to the session store for session data for this client and add this data to the request object.
  • End-of-session middleware processing
  • Later, in express processing of this HTTP request, it gets into the corresponding request handler. Session data from the session store for this particular http client is already bound to the request object and is available to the request handler used.
+5
source share

All Articles