如何获取在socket.io中连接了socket.io之后添加的会话

时间:2019-04-07 15:02:20

标签: node.js express socket.io express-session

我想在登录后的会话中获得user属性,但是当我在登录后设置会话时,socket.request.session不变,其中没有user属性。但是我可以在router.post中得到它。

我尝试在router.post()/router.get()中编辑会话,socket.request.session仍然没有改变。

index.js

const io = require('socket.io').listen('8082', { origins: '*' })
const schedule = require('node-schedule')

io.set('transports', [
  'websocket',
  'flashsocket',
  'htmlfile',
  'xhr-polling',
  'jsonp-polling',
  'polling'
])
io.set('origins', '*:*')

const app = new express()

const sessionStore = new session.MemoryStore({ reapInterval: 3600 * 1000 })
const sessionMiddleware = session({
    secret: 'Stefanie Sun',
    store: sessionStore,
    resave: false, 
    saveUninitialized: true,
    cookie: { 
        maxAge: 8 * 3600 * 1000,
        secure: false
  }, 
    rolling: true
})
io.use((socket, next) => {
  sessionMiddleware(socket.request, socket.request.res, next);
})
app.use(sessionMiddleware)
routes(app)

io.on('connection', (socket) => {
  const comment_schedule = schedule.scheduleJob('*/10 * * * * *', async () => {         /** 10s查询一次是否有新的内容 **/
    const COOKIE_STR = socket.request.session
    console.log(COOKIE_STR)
  })
})

router.js

...
router.post('/pagelist', (req, res, next) => {
  req.session.user = { username: 'test1', gender: 'x', bio: 'this is a test' }
  console.log(req.session)
  res.status(200).json({ code: 'OK' })
}
app.user('/api/page', router)

登录后访问/api/page/pagelist时,希望可以在router.post的socket.requestreq.session中获得相同的会话, 但是socket.request.session

Session {
  cookie:
   { path: '/',
     _expires: 2019-04-07T22:57:13.379Z,
     originalMaxAge: 28800000,
     httpOnly: true,
     secure: false } }

但在router.post req.session中是

Session {
  cookie:
   { path: '/',
     _expires: 2019-04-07T22:57:48.146Z,
     originalMaxAge: 28799999,
     httpOnly: true,
     secure: false },
  user:
   { 
     username: 'test1',
     gender: 'x',
     bio: 'this is a test'
}}

我希望在socket.request.session中我也能得到 user属性。

我的fontend项目是Vue.js。然后在home.vue中设置socket.on('event')。在页面登录之前,我连接了socket.io,登录后,我在会话中设置了用户属性,但在socket.request.session中却找不到该属性。

前端登录代码

// api.js
export const loginApi = ({ username, password } = { username: '', password: '' }) => {
    const data = {
        username,
        password
    };
    return axios.request({
        url: '/api/signin',
        data: qs.stringify(data),
        method: 'post'
    })
}

// login.vue
submit() {
    loginApi({ username: this.username, password: this.password})
       .then((result: any) => {
            this.$toast.success('login success');
            this.Cookies.set('user', this.username, { expires: 7 });
            getUserInfo(this.username).then((res: any) => {
                const { data } = res;
                localStorage.setItem('user', JSON.stringify(data));
                const url = this.redirect && this.redirect || '/pages';
                this.$router.push(url);
            })
        })
}

0 个答案:

没有答案