2

我想在会话中保留一些数据。我使用 MongoDB 作为会话存储。

我准备了简单的代码来做到这一点。但它,不起作用。我收到了这个错误:

类型错误:无法设置未定义的属性“myVariable”

这是我的代码:

var express = require('express');
var app = require('express')();
var http = require('http')
var server = require('http').Server(app);
var io = require('socket.io')(server);
var get_ip = require('ipware')().get_ip;
var Sequelize = require('sequelize');
var url = require("url");
var crypto = require('crypto');
var cookieParser = require('cookie-parser');
var Session      = require('express-session');
var MongoStore  = require('connect-mongo')(Session);
var mongoose = require('mongoose');
var url =require('url');



app.use(cookieParser());

app.use(Session({
    cookie: { maxAge: 1000*60*2 } ,
    secret: "session secret" ,
    resave: true,
    saveUninitialized: true,
    store:new MongoStore({
        db: 'linchat'
    })
}));



server.listen(3000);

io.on('connection', function (socket) {

    socket.on('join', function(href, referer){
        socket.request.session.myVariable = 'my session variable value';
        console.log('save on to session');
    })


});

我做错了什么?我使用:“express”:“4.12.3”,“socket.io”:“1.3.5”

编辑 我也尝试使用 express-socket.io-session 包:

var express = require('express');
var app = require('express')();
var http = require('http')
var server = require('http').Server(app);
var io = require('socket.io')(server);
var get_ip = require('ipware')().get_ip;
var Sequelize = require('sequelize');
var url = require("url");
var crypto = require('crypto');
var cookieParser = require('cookie-parser');
var Session      = require('express-session');
var MongoStore  = require('connect-mongo')(Session);
var mongoose = require('mongoose');
var url =require('url');


app.use(cookieParser());


var session = require("express-session")({
    secret: "my-secret",
    resave: true,
    saveUninitialized: true,
    store:new MongoStore({
        db: 'linchat'
    })
});
app.use(session);
io.use(require("express-socket.io-session")(session));

server.listen(3000);

io.on('connection', function (socket) {
    socket.on('join', function(href, referer){
        if(socket.handshake.session.views){
            socket.handshake.session.views +=1;
        } else {
            socket.handshake.session.views =1;
        }
        console.log(socket.handshake.session.views);
    })


});

但我 console.log() 总是返回 '1'

4

0 回答 0