Can I access a cookie from Socket.io?

前端 未结 4 1804
孤街浪徒
孤街浪徒 2020-12-05 12:55

I want to set some user information in a cookie and be able to access it on connection, is this possible?

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 13:39

    After looking to the engine.io source code you can set cookies using:

    var io = require('socket.io')(3000);
    
    io.use((socket, next) => {
        socket.conn.transport.once('headers', (headers) => {
    
            headers['set-cookie'] ="sess=test;"; });
    
        next();
    });
    

    this code could conflict with the engine.io code that set the sid cookie. as both HTTP/1.1 and HTTP/2 headers are case-insensitive and engine.io use 'Set-Cookie' in the headers object adding a lowercase object name 'set-cookie' would avoid this problem.

提交回复
热议问题