如何在请求之外以快速方式访问会话?
我知道我可以使用
function(req, res) {
req.session
}
express。但是我需要访问响应函数之外的会话。我该怎么做呢?
我正在使用 socket.io 传递用于添加帖子和评论的信息。因此,当我在服务器端收到socket.io消息时,我需要使用会话来验证发布信息的人。然而,由于这是通过 socket.io 完成的,因此没有 req/res。
I know that I can use
function(req, res) {
req.session
}
using express. However I need to access the session outside of the response function. How would I go about doing that?
I'm using socket.io to pass information for adding posts and comments. So when I receive the socket.io message on the server-side, I need to verify the person posting the information by using the session. However since this is being done via socket.io there is no req/res.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我想我有不同的答案。
code:
那么你应该在 req 处定义一个会话密钥,就像:
code:
最后,你可以这样得到它:
code:
我昨天测试过它,效果很好。
I think I have a different answer.
code:
then you should define a session key at req,just like :
code:
finally,you can get it this way:
code:
I had test it yesterday, it worked well.
使用 socket.io,我以简单的方式完成了此操作。我假设您的应用程序有一个对象,比如说 MrBojangle,对于我的来说,它称为 Shished:
然后在您的授权方法上,我使用 MongoDB 进行会话存储:
然后在模型中保存记录之前,您可以执行以下操作:
model._author = shished.getHandshakeValue(socket, 'userId' );
Using socket.io, I've done this in a simple way. I assume you have an object for your application let's say MrBojangle, for mine it's called Shished:
Then on your authorization method, I'm using MongoDB for session storage:
Then before saving a record in the model, you can do:
model._author = shished.getHandshakeValue( socket, 'userId' );
我相信检查
socket.handshake
应该可以获取会话:当客户端与 socket.io 服务器建立套接字连接时,客户端会发送一个 WebSocket 握手请求。我上面所做的是从握手中获取会话 ID。
I believe checking
socket.handshake
should get you the session:When the client establishes a socket connection with your socket.io server, the client sends a WebSocket handshake request. What I'm doing above is grabbing the session ID from the handshake.
假设您的 socket.io 代码看起来有点像这样:
请求是
client.request
如上例所示。编辑:
作为一件单独的事情,也许这会有所帮助:
https://github.com/aviddiviner/Socket.IO-sessions
Assuming your socket.io code looks kinda like this:
The request is
client.request
as shown in the example above.Edit:
As a separate thing, maybe this would help:
https://github.com/aviddiviner/Socket.IO-sessions