express-session通过设置req.session.userInfo之后获取失败

本文探讨了在使用Express-Session进行用户会话管理时遇到的问题,即在Vue应用中未能正确验证已登录用户的权限。问题源于请求未携带cookies,导致服务器无法识别已登录状态。解决方法是在Vue的main.js中设置axios.defaults.withCredentials为true,确保跨域请求携带cookies。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

express-session通过设置req.session.userInfo之后获取失败

需要登录权限的时候就出问题了,node在登录后回将session保存在req.session.user上,在后面需要权限的时候去取出来验证,如果有req.session.user则通过验证,如果没有则提示登录。我在登录后能正确提示成功,但是到需要验证的功能上还是不能通过权限验证,通过google发现,在请求的时候没有带cookies,所以服务器不能认为你是一个已经登录的用户。以上是原因。
解决方法:在Vue项目的main.js中设置
//发送请求时携带cookie
axios.defaults.withCredentials= true;

参考文章:https://www.jianshu.com/p/c5fdfddd45a0

const express = require('express'); const bodyParser = require('body-parser'); const request = require('request'); const crypto = require('crypto'); const app = express(); app.use(bodyParser.json()); // 从环境变量获取配置,避免硬编码敏感信息 const wx = { appid: process.env.WX_APPID || 'wx2c38221f8ddea524', secret: process.env.WX_SECRET || '785ca52827eed993f2a7d3b55053dad0' }; // 使用更安全的方式存储会话和用户数据 const db = { session: {}, user: {} }; // 生成安全的token function generateToken(openid) { const timestamp = new Date().getTime(); const randomStr = Math.random().toString(36).substr(2, 15); const hash = crypto.createHash('sha256'); hash.update(openid + timestamp + randomStr + wx.secret); return hash.digest('hex'); } // 登录接口 app.post('/login', (req, res) => { console.log('login code: ' + req.body.code); // 构建微信登录请求URL const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${wx.appid}&secret=${wx.secret}&js_code=${req.body.code}&grant_type=authorization_code`; request(url, (err, response, body) => { if (err) { console.error('请求微信接口失败', err); return res.status(500).json({ err: '请求微信接口失败' }); } try { const session = JSON.parse(body); if (session.errcode) { console.error('微信接口返回错误', session); return res.status(400).json({ err: session.errmsg }); } if (session.openid) { // 生成安全的token const token = generateToken(session.openid); // 存储会话信息,设置过期时间(2小时) const expiresIn = 2 * 60 * 60 * 1000; // 毫秒 db.session[token] = { ...session, expires: Date.now() + expiresIn }; // 如果是新用户,初始化用户信息 if (!db.user[session.openid]) { db.user[session.openid] = { credit: 100, createTime: new Date().toISOString(), lastLoginTime: new Date().toISOString() }; } else { // 更新最后登录时间 db.user[session.openid].lastLoginTime = new Date().toISOString(); } return res.json({ token: token, expiresIn: expiresIn / 1000 // 秒 }); } else { console.error('未获取到openid', session); return res.status(400).json({ err: '未获取到openid' }); } } catch (parseErr) { console.error('解析session失败', parseErr); return res.status(500).json({ err: '解析session失败' }); } }); }); // 检查登录状态 app.get('/checklogin', (req, res) => { const token = req.query.token; const session = db.session[token]; console.log('checklogin: ', session); // 检查token是否存在且未过期 const isLogin = session && session.expires > Date.now(); // 如果token已过期,清理过期数据 if (session && !isLogin) { delete db.session[token]; } // 将用户是否已经登录的布尔值返回给客户端 res.json({ is_login: isLogin }); }); // 获取用户积分 app.get('/credit', (req, res) => { const token = req.query.token; const session = db.session[token]; // 检查token是否存在且未过期 if (!session || session.expires <= Date.now()) { return res.status(401).json({ err: '用户未登录或登录已过期' }); } if (db.user[session.openid]) { res.json({ credit: db.user[session.openid].credit }); } else { res.status(404).json({ err: '用户不存在' }); } }); // 更新用户积分 app.post('/updateCredit', (req, res) => { const token = req.body.token; const session = db.session[token]; // 检查token是否存在且未过期 if (!session || session.expires <= Date.now()) { return res.status(401).json({ err: '用户未登录或登录已过期' }); } const openid = session.openid; const user = db.user[openid]; if (!user) { return res.status(404).json({ err: '用户不存在' }); } // 增加或减少积分 if (req.body.change) { user.credit = Math.max(0, user.credit + req.body.change); } res.json({ success: true, credit: user.credit }); }); // 退出登录 app.post('/logout', (req, res) => { const token = req.body.token; if (db.session[token]) { delete db.session[token]; } res.json({ success: true }); }); app.listen(3000, () => { console.log('server running at http://127.0.0.1:3000'); }); // pages/Logo/Logo.js Page({ data: { userInfo: null }, onLoad(options) { }, // 处理登录 handleLogin() { wx.login({ success: (res) => { if (res.code) { // 获取用户信息 this.getUserProfile(res.code); } else { console.log('登录失败:', res.errMsg); wx.showToast({ title: '登录失败', icon: 'none' }); } }, fail: (err) => { console.log('请求失败:', err); wx.showToast({ title: '网络错误', icon: 'none' }); } }); }, // 获取用户信息 getUserProfile(code) { wx.getUserProfile({ desc: '用于完善会员资料', success: (userRes) => { const userInfo = userRes.userInfo; // 这里可以将 userInfo 和 res.code 发送到后端进行验证 // 示例:假设后端验证成功并返回 token const token = '123456'; wx.setStorageSync('userInfo', { nickName: userInfo.nickName, avatarUrl: userInfo.avatarUrl, token }); wx.showToast({ title: '登录成功', icon: 'success' }); setTimeout(() => { wx.switchTab({ url: '/pages/train/train' // 假设主页面是 train 页面 }); }, 1500); }, fail: (err) => { console.log('获取用户信息失败:', err); wx.showModal({ title: '授权提示', content: '为了给您提供更好的服务,请授权获取您的用户信息。', confirmText: '重新授权', success: (modalRes) => { if (modalRes.confirm) { this.getUserProfile(code); } } }); } }); }, // 清除缓存 clearCache: function () { wx.clearStorageSync(); wx.showToast({ title: '缓存已清除', icon: 'success' }); } }); <!--pages/Logo/Logo.wxml--> <view class="container"> <button bindtap="handleLogin">点击登录</button> </view> /* pages/Logo/Logo.wxss */ .container { display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100vh; padding: 0 20px; } input { width: 100%; height: 40px; margin-bottom: 20px; border: 1px solid #ccc; border-radius: 5px; padding: 0 10px; } button { width: 100%; padding: 10px 20px; background-color: #5495E6; color: white; border: none; border-radius: 5px; font-size: 16px; }
最新发布
06-12
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值