1.用户第一次登录的时候就把返回的openid存到缓存里面
getuserinfo(e) {
var that = this
var userinfoDetails = {}
userinfoDetails = e.detail.userInfo
uni.getUserInfo({
provider: 'weixin',
success: function () {
uni.login({
success:function(res){
uni.request({
url: that.apiUrl + 'small/index/GetOpenid?code=' + res.code,
success: (res) => {
console.log(res)
if (res.data.openid) {
//把openid存到缓存里面
uni.setStorageSync('openid', res.data.openid)
userinfoDetails.openid = res.data.openid
}
}
})
}
})
}
});
},
2.新建config.js封装请求
const app = {
apiUrl: 'https://aaa.bbb.com/', //请求的域名
openidRequest(obj) {
try {
const openid = uni.getStorageSync('openid');
if (openid) {
if(obj.data) {
obj.data["openid"] = openid;
} else {
obj.data = {"openid": openid};
}
obj.url = this.apiUrl + obj.url;
uni.request(obj)
} else {
console.log("获取不到openid")
}
} catch (e) {
console.log(e)
console.log("获取不到openid")
}
},
}
export default app;
3.在页面调用需要用到openid为参数的请求
import app from '../../common/config.js'
export default {
onLoad() {
this.getTeamlist()
},
methods: {
getTeamlist() {
var that = this
app.openidRequest({
url: 'test/abc', //如果请求的地址为:https://aaa.bbb.com/test/abc,那么这里url只需要写'test/abc'
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded',
},
success:(res) =>{
this.teamlist = res.data.teamlist
}
})
}
},
}
下面是token的,只是把openid换成userToken
config.js
const app = {
apiUrl: 'http://216:18080/webcase/', //请求的地址
baseRequest(obj) {
try {
const userToken = uni.getStorageSync('userToken');
if (userToken) {
if (obj.header) {
obj.header["token"] = userToken;
} else {
obj.header = { "token": userToken };
}
obj.url = this.apiUrl + obj.url;
uni.request(obj)
}
else{
console.log("获取不到userToken")
}
} catch (e) {
console.log(e)
console.log("获取不到userToken")
}
},
}
export default app;
需要使用的页面
import app from "@/api/apiConfig"
getUserStatus() {
app.baseRequest({
url: 'getUserStatus',
method: 'POST',
success: (res) => {
// 用户状态存到缓存中去
try{
uni.setStorageSync('userStatus', res.data.data.type)
uni.setStorageSync('userAgentInfo',res.data.data)
}catch(e){
//TODO handle the exception
}
if(res.data.data.type == 2) {
this.getLawInfo()
} else {
this.yhju= false
}
}
})
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。