- 后台express => /app.js
import { client, redis } from "./config/redis"
const session = require('express-session')
const RedisStore = require('connect-redis')(session)
app.use(session({
name: 'session-name', // 这里是cookie的name,默认是connect.sid
secret: 'my_session_secret', // 建议使用 128 个字符的随机字符串
resave: true, //强制保存session即使他没有什么变化
saveUninitialized: false, //强制将来初始化的session存储
store: new RedisStore({ client: client }),
cookie: { maxAge: 60 * 60 * 1000, httpOnly: true }
}));
// 拦截器,对需要登陆的页面进行拦截
app.all(['/order/*','/address/*'], async function (req, res, next){
// 略
})
- 后台express => /routes/user.js
const express = require('express');
const router = express.Router();
const crypto = require('crypto')
const qs = require('querystring')
const config = require("../config/config")
import Result from "../config/Result";
router.post('/jscode2session', async function (req, res, next) {
let { js_code } = req.body
if (js_code){
const content = qs.stringify({
appid: config.weChat[config.model].AppID,
secret: config.weChat[config.model].AppSecret,
js_code: js_code,
grant_type: 'authorization_code',
})
request.get( 'https://api.weixin.qq.com/sns/jscode2session?' + content, async function (error, response, body) {
if (!error && response.statusCode === 200) {
let { openid, session_key } = JSON.parse(body)
if ( openid && session_key ){
let user = await dao.getUserByOpenid(openid) // 查询是不是新用户
let session_id = crypto.createHash('md5').update(openid+session_key).digest('hex')
res.cookie('session_id', session_id, {maxAge: 20*60*1000})
if (user){
req.session.openid = openid
req.session.session_key = session_key
req.session.user = user
res.send(Result.OK)
}else {
res.send(Result.NEW_USER)
}
}else {
res.send(Result.TOKEN_EXPIRED)
}
}
})
}else {
res.send(Result.PARAMS_ERROR)
}
})
module.exports = router
- 微信小程序浏览器,储存传回来的cookie
wx.request({
url: 'https://efuser.test.com/api/user/jscode2session',
data: {
js_code: _code,
},
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded' // 默认是json
},
success: function (res) {
if (res && res.header && res.header['Set-Cookie']) {
var cookieArr = new Array()
res.cookies.forEach((item, index, array) => {
cookieArr.push(item.split(";")[0]);
})
// wx.setStorageSync('cookieKey', res.header['Set-Cookie']);
// 对头部不做任何处理,后台是获取不到session的,格式不正确;浏览器点击F12可以查看cookie的正确格式,
wx.setStorageSync('cookieKey', cookieArr.join(";"))
}
}
})
请求Cookie
名称 | 值 |
---|---|
session_id | 310dcbbf4cce62f762a2aaa148d556bd |
session-name | s%3AQSiHC_QO-x6VMVn5E9rKih4MSO_sZaP6.hAgAui6TH4TsbB5SO72YHSYGxzUAbcrZ |
- 微信小程序浏览器不保存cookie,请求接口需要带上cookie
wx.request({
url: 'https://efuser.test.com/api/test',
method: 'get',
header: {
'content-type': 'application/x-www-form-urlencoded', // 默认是json
'cookie': wx.getStorageSync("cookieKey")
},
success: function (res) {
console.info(res.data)
}
})
- redis存储格式
{
"user": {
"id": 1,
"username": "admin",
"password": "6512bd43d9caa6e02c990b0a82652dca",
"real_name": "wgq",
"nickname": "Anna Clark",
"area_code": 86,
"phone": "15000000000",
"gender": 2,
"country": null,
"province": null,
"city": null,
"avatar_url": null,
"create_time": "1984-08-26 19:56:56",
"update_time": "2020-10-12 15:15:41",
"wechat_openid": "ooooooooooooooooooo",
"wechat_union_id": null,
"is_lock": 0,
"state": 1
},
"cookie": {
"originalMaxAge": 3600000,
"expires": "2020-10-26T07:19:31.050Z",
"httpOnly": true,
"path": "/"
},
"openid": "ooooooooooooooooooo",
"session_key": "ooooooooooooooooooo",
}
- 至此,在后端就可以使用
req.session.user
获取到保存到session中的用户信息。使用req.cookies[xxx]
获取到保存到cookie中的数据