1、背景
解决微信小程序session不能使用,session 不唯一问题。
操作流程
1.调用登录请求
2.获取登录请求中的set-cookie 信息
3. 保存到本地缓存
4.每次调用加入请求头中
例如: 微信小程序调用用户信息。
login. wxml
<button bindtap="getUserInfo">getUserInfo</button>
login.js
getUserInfo(){
// 获取用户信息
httpUtils.request({
showLoading: true,
url: `/user/get/login`,
message: "正在获取用户数据..."
}).then(res => {
this.setData(
res.data.data
)
ui.showToast(res.data.errorMsg)
}).catch(err => {
console.log('ERROR')
});
},
控制台显示未登录
发现后台没有session传入
2、步骤
2.1首次请求
首次请求获取 header 中的Set-Cookie 作为cookie信息
直接开始登录流程
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
if (res.code) {
//发起网络请求
httpUtils.request({
method: "GET", showLoading: true,url: `/wx/user/wxLogin`,message: "正在登录",
data: {
code: res.code
}
}).then(res => {
if(res.header["Set-Cookie"]){
wx.setStorageSync('sessionid', res.header["Set-Cookie"]);
}
this.globalData.userInfo = res.data.data
ui.showToast(res.data.errorMsg)
}).catch(err => {
console.log('ERROR')
});
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
注意:每次重新登录前要删除缓存信息
wx.removeStorageSync('sessionid')
2.2存入微信小程序缓存
if(res.header["Set-Cookie"]){
wx.setStorageSync('sessionid', res.header["Set-Cookie"]);
}
SESSION=MjMxZDM3NmYtYzgzYy00NDc0LWExODYtOWRmODI0N2M1NTMy; Path=/api; HttpOnly; SameSite=Lax
2.3将cookie加入请求头
let header = {
'content-type': 'application/json', // 默认值
}
let session_id = wx.getStorageSync('sessionid');//本地取存储的sessionID
if (session_id != "" && session_id != null) { //本地session存在,则放到header里
header.Cookie = session_id;
}
2.4请求
最后直接使用wx.request API调用接口,大功告成。
重新调用后
附录
httpUtils.js
const ui = require('./ui');
const BASE_URL = 'http://XXXXXX:8890/api'
/**
* 网络请求request
* obj.data 请求接口需要传递的数据
* obj.showLoading 控制是否显示加载Loading 默认为false不显示
* obj.contentType 默认为 application/json
* obj.method 请求的方法 默认为GET
* obj.url 请求的接口路径
* obj.message 加载数据提示语
*/
function request(obj) {
return new Promise(function (resolve, reject) {
if (obj.showLoading) {
ui.showLoading(obj.message ? obj.message : '加载中...');
}
var data = {};
if (obj.data) {
data = obj.data;
}
var contentType = 'application/json';
if (obj.contentType) {
contentType = obj.contentType;
}
var method = 'GET';
if (obj.method) {
method = obj.method;
}
let header = {
'content-type': 'application/json', // 默认值
}
let session_id = wx.getStorageSync('sessionid');//本地取存储的sessionID
if (session_id != "" && session_id != null) { //本地session存在,则放到header里
header.Cookie = session_id;
}
wx.request({
url: BASE_URL + obj.url,
data: data,
method: method,
//添加请求头
header: header,
contentType: contentType,
//请求成功
success: function (res) {
console.log('===========================================================================================')
console.log('== 接口地址:' + obj.url);
console.log('== 接口参数:' + JSON.stringify(data));
console.log('== 请求类型:' + method);
console.log("== 接口状态:" + res.statusCode);
console.log("== 接口数据:" + JSON.stringify(res.data));
console.log('===========================================================================================')
if (res.statusCode == 200) {
resolve(res);
} else if (res.statusCode == 401) {//授权失效
reject("登录已过期");
jumpToLogin();//跳转到登录页
} else {
//请求失败
reject("请求失败:" + res.statusCode)
}
},
fail: function (err) {
//服务器连接异常
console.log('==========================================================================================')
console.log('== 接口地址:' + url)
console.log('== 接口参数:' + JSON.stringify(data))
console.log('== 请求类型:' + method)
console.log("== 服务器连接异常")
console.log('==========================================================================================')
reject("服务器连接异常,请检查网络再试");
},
complete: function () {
ui.hideLoading();
}
})
});
}
//跳转到登录页 小程序每次启动登录 暂时没有登录页面
function jumpToLogin() {
}
module.exports = {
request,
}
ui.js
控制模态框
export const showToast = function(content,duration) {
if(!duration) duration = 2000
wx.showToast({
title: content,
icon: 'none',
duration: duration,
})
}
var isShowLoading = false
export const showLoading = function(title) {
if(isShowLoading) return
wx.showLoading({
title: title?title:'',
mask:true,
success:()=>{
isShowLoading = true
}
})
}
export const hideLoading = function() {
if(!isShowLoading) return
isShowLoading = false
wx.hideLoading()
}
app.js
// app.js
const httpUtils = require('./utils/httpUtils')
const ui = require('./utils/ui')
App({
onLaunch() {
//删除缓存 重新登录 获取会话
wx.removeStorageSync('sessionid')
// 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
if (res.code) {
//发起网络请求
httpUtils.request({
method: "GET", showLoading: true,url: `/wx/user/wxLogin`,message: "正在登录",
data: {
code: res.code
}
}).then(res => {
// 保存set-cookie到缓存中
if(res.header["Set-Cookie"]){
wx.setStorageSync('sessionid', res.header["Set-Cookie"]);
}
// 用户信息保存在全局变量
this.globalData.userInfo = res.data.data
ui.showToast(res.data.errorMsg)
}).catch(err => {
console.log('ERROR')
});
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
wx.getSystemInfo({
success: e => {
this.globalData.StatusBar = e.statusBarHeight;
let custom = wx.getMenuButtonBoundingClientRect();
this.globalData.Custom = custom;
this.globalData.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
}
})
},
globalData: {
userInfo: null,
}
})