Node.js & Express session problem

前端 未结 4 1990
闹比i
闹比i 2020-12-28 09:06

I\'m having a problem with sessions, where sometimes the session variable I just set is undefined on the next page request. I typically have to go through the flow

4条回答
  •  遥遥无期
    2020-12-28 09:34

    In Connect's session, any handler can set req.session.anything to any value, and Connect will store the value when your handler calls end(). This is dangerous if there are multiple requests in flight at the same time; when they finish, one session value will clobber the other. This is the consequence of having such a simple session API (or see the session source directly), which has no support to atomically get-and-set session properties.

    The workaround is to try to give the session middleware as few of the requests as necessary. Here are some tips:

    1. Put your express.static handler above the session middleware.
    2. If you can't move up some handlers that don't need the session, you can also configure the session middleware to ignore any paths that don't use req.session by saying express.session.ignore.push('/individual/path').
    3. If any handler doesn't write to the session (maybe it only reads from the session), set req.session = null; before calling res.end();. Then it won't be re-saved.

    If only one request does a read-modify-write to the session at a time, clobbering will be less likely. I hope that in the future, Connect will have a more precise session middleware, but of course the API will be more complicated than what we have now.

提交回复
热议问题