简体   繁体   English

消息上的Express WebSockets获取Cookie信息

[英]Express websockets on message get cookie info

I have an express web socket application. 我有一个快速的Web套接字应用程序。

In the onmessage function, I would like to access the cookies of the client that sent the message. onmessage函数中,我想访问发送消息的客户端的cookie。

The reason for this is that I'm making a game and I have the user login. 这样做的原因是我正在做游戏,并且已经有用户登录名。 I need to check what to name cookie is so that I control the correct player. 我需要检查Cookie的name ,以便控制正确的播放器。

This is what I've got so far: 到目前为止,这是我得到的:

var express = require('express');
var expressWs = require('express-ws');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var app = express();

app.use(cookieParser('secretkey123'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}))

expressWs = expressWs(app);

app.get('/', function(req, res) {
    // stuff for logging in
})

app.post('/', function(req, res) {
    // stuff for logging in
})

app.get('/logout', function(req, res) {
    res.clearCookie('name');
    res.redirect('/');
    // more stuff for logging in
})

app.ws('/ws', function(ws, req) {
    ws.on('open', function() {
        // how do I check when a connection is opened?
    })
    ws.on('message', function(msg) {
        // who sent the message? how do I get the cookie info to check the user who send it?
    })
    ws.on('close', function() {
        // the've disconnected
    })
})

var server = app.listen(8000, function () {
   var host = server.address().address
   var port = server.address().port
})

Is this possible? 这可能吗?

Also, where do I check when a websocket connection is opened? 另外,在哪里检查何时打开Websocket连接?

I tried the 'open' event but it doesn't seem to be working. 我尝试了“公开”活动,但似乎没有成功。

Thanks for the help in advance! 我在这里先向您的帮助表示感谢!

I figured out how to do it! 我想出了怎么做!

I forgot that the req argument can be accessed inside the other functions. 我忘记了req参数可以在其他函数中访问。

This means in the on message function you can just do this: 这意味着在on message函数中,您可以执行以下操作:

ws.on('message', function(msg) {
    req.cookies.username //do stuff
});

The connection open code can be done before you setup any of the events: 可以在设置任何事件之前完成连接打开代码:

app.ws('/ws', function(ws, req) {
    // connection open code here
    ws.on('message', function(msg) {
        // connection message code here
    })
})     

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM