我想在登录后的会话中获得user
属性,但是当我在登录后设置会话时,socket.request.session
不变,其中没有user
属性。但是我可以在router.post中得到它。
我尝试在router.post()/router.get()
中编辑会话,socket.request.session
仍然没有改变。
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.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.request
和req.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);
})
})
}