Javascript how to reference an Express-Session on the client

家住魔仙堡 提交于 2020-12-12 09:55:06

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/42471888/javascript-how-to-reference-an-express-session-on-the-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!