且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Node.js&快递会话问题

更新时间:2023-08-19 22:00:22

在Connect的会话中,任何处理程序都可以将 req.session.anything 设置为任何值,并且当处理程序调用端()。如果同时有多个飞行请求,这是危险的;当他们完成时,一个会话值会破坏另一个会话值。这是使用如此简单的会话API (或参见激情源直接),它不支持原子获取和设置会话属性。

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. express.static 处理程序置于会话中间件之上。

  2. 如果您无法向上移动一些不需要会话的处理程序,您还可以配置会话中间件以忽略任何不使用 req.session 通过说 express.session.ignore.push('/ individual / path')

  3. 如果任何处理程序没有写入会话(可能只是从会话中读取),请在调用 req.session = null; > res.end(); 。然后它将不会被重新保存。

  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.

如果只有一个请求一次对会话执行读取 - 修改 - 写入,破坏的可能性会降低。我希望将来Connect会有一个更精确的会话中间件,但当然API会比我们现在的更复杂。

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.