封裝接口請求,我們的業(yè)務(wù)需要在header上加token和openid帘不,可以根據(jù)自己的業(yè)務(wù)邏輯進(jìn)行項(xiàng)目改變。
const baseUrl = "xxx";
const http = ({
url = '',
param = {},
type = 'json',
callback = '',
...other
} = {}) => {
wx.showLoading({
title:'請求中...',
})
let timeStart = Date.now();
return new Promise((resolve, reject) => {
wx.request({
url: baseUrl + url,
data:param,
header: {
'content-type': type == 'json' ? 'application/json' : 'application/x-www-form-urlencoded',
'token':getToken(),
'openid': getOpenid() || getCouldOpenid().then(openid => openid)
},
...other,
complete: res => {
wx.hideLoading();
console.log(`耗時(shí)${Date.now() - timeStart}`);
//重新請求完token杨箭,再次執(zhí)行后的請求在這里攔截
if(callback) { callback(res.data); return }
if(res.statusCode >=200 && res.statusCode < 300) {
/**
* 這是我們自定義的接口狀態(tài)判斷參數(shù)
* status_code == 401 為token過期狀態(tài)需要重新獲取token
* status_code == 403 為用戶未登陸狀態(tài)寞焙,需要走登錄邏輯
*/
if (res.data.status_code == 401 || res.data.status_code == 403) {
if (res.data.status_code == 403) { //用戶登陸并獲取token
wx.navigateTo({
url: '/pages/loginIn/loginIn',
})
} else if (res.data.status_code == 401) { //token過期
getNewToken(url, param).then(() => {
http({
url,
param,
method: 'post',
callback: resolve
})
})
}
} else {
resolve(res.data)
}
} else {
reject(res);
}
})
})
}
//獲取新token
const getNewToken = (url, param) => {
return new Promise((resolve, reject) => {
wx.request({
url: baseUrl + 'user!appLogin.action',
data: {
openid: getOpenid(),
},
header: {
'content-type': 'application/x-www-form-urlencoded'
},
method: 'post',
success: function (res) {
console.log(res);
if (res.data.success) {
wx.setStorageSync('token', res.data.data.token);
wx.setStorageSync('personal', res.data);
resolve(res)
} else {
if (res.data.status_code == 403) {
wx.navigateTo({
url: '/pages/loginIn/loginIn',
})
}
}
},
})
})
}
//獲取token
const getToken = () => {
let token = wx.getStorageSync('token') || '';
return token;
}
//獲取openid
const getOpenid = () => {
let openid = wx.getStorageSync('openid') || null
return openid;
}
獲取openid的方法, 我是使用的小程序云開發(fā)獲取openid 互婿,也可以使用code跟后臺(tái)換取openid
//獲取openID
const getCouldOpenid = () => {
return new Promise((resolve, reject) => {
wx.cloud.callFunction({
name: 'login',
data: {},
success: res => {
console.log('[云函數(shù)] [login] user openid: ', res.result.openid)
resolve(res.result.openid);
wx.setStorageSync('openid', res.result.openid)
},
fail: err => {
console.error('[云函數(shù)] [login] 調(diào)用失敗', err)
}
})
})
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者