admin管理员组

文章数量:1303448

In my server I have created an express-session. I want to store in this a check for if the user has logged in or not. I do not know how to access this express-session on the non-server side of the code.

Basically if the user is logged in I will then edit a page the user sees. I will only know to edit the page if the user is logged in or not which would require me to access the express session.

In my server I have created an express-session. I want to store in this a check for if the user has logged in or not. I do not know how to access this express-session on the non-server side of the code.

Basically if the user is logged in I will then edit a page the user sees. I will only know to edit the page if the user is logged in or not which would require me to access the express session.

Share Improve this question asked Feb 26, 2017 at 17:38 MoStackMoStack 492 silver badges3 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

You cannot access session data directly from the client. It is stored server-side only. The session cookie only contains a session ID, none of the actual session state.

To get access to the logged in state, you have a couple options:

  1. When you render the page, insert a Javascript variable in the page that has the logged in state in it and perhaps the userID of the logged in user. Then, your client side JS can simply check that variable to know the state. This is simple to do if you are using any sort of template engine for rendering your pages. It's also mon to set a loggedIn classname on some high level tag such as the tag in the page. This allows CSS to automatically adjust based on whether the user is logged in or not (for example, to hide the login button).

  2. You can check for the existence of the session cookie at all. If there is no session cookie present, then the user cannot be logged in. The fact that a session cookie is present does NOT necessarily mean that the user is logged in. That could be an old cookie or could even be a cookie from a different user. But, the absence of the cookie would mean that no user is logged in.

  3. You could query the server and ask it. You would have to specify what userID you are asking about and the server could then check to see if the current session cookie is valid and belongs to that specific user.

Personally, I would likely do some variation of option #1.

You cannot access express session data on the client side (e.g. browser). It is accessible only on the server side.

Note Session data is not saved in the cookie itself, just the session ID. Session data is stored server-side.

You'll need to add some endpoint which checks session to get information about user status.

本文标签: nodejsJavascript how to reference an ExpressSession on the clientStack Overflow