How is the express req.session object persisted?

后端 未结 1 1660
有刺的猬
有刺的猬 2020-12-24 07:25

I\'m very new to learning Node and Express, and I\'m still trying to wrap my head around the code flow with express. Suppose we have code that looks like this in a session.j

相关标签:
1条回答
  • 2020-12-24 08:02

    There's an overall session data structure that stores all session info (like a global, but it could also be in a database - just something that is persistent at least across connections). Each client's session data uses one unique key to index into the session store to get the session data for that client.

    Part of establishing a session for a given browser client is creating a unique client key (which will usually be stored in a cookie) that becomes the index into the global session object.

    On an incoming http request, Express middleware that supports the session checks a particular client cookie and if that particular cookie is found on the http request and is found in the global session object/database, then it adds that session's stored info to the request object for the http request handler to later use.

    So, here's a typical sequence:

    1. Incoming HTTP request.
    2. Middleware checks for session cookie.
    3. If session cookie not there, then create one and, in the process created a unique id to identify this http client.
    4. In the persistent session store, initialize the session for this new client.
    5. If session cookie is there, then look in the session store for the session data for this client and add that data to the request object.
    6. End of session middleware processing
    7. Later on in the Express processing of this http request, it gets to a matching request handler. The session data from the session store for this particular http client is already attached to the request object and available for the request handler to use.
    0 讨论(0)
提交回复
热议问题