route
request
config
api
.gitignore config.js
【一】:config.js
const web = 'http://test.www.net'
const webUrl = web+'/api/userapi'
export default{
webUrl,
web
}
【二】:api.js
import config from './config.js'
import route from './route.js'
import request from './request.js'
import Vue from 'vue'
const api = {}
// 获取用户信息
api.getUserFindApi = ()=> {
console.log('api--全局定义接口-获取用户信息and挂载')
request.globalRequest(route._getUserFind).then((res)=>{
Vue.prototype.$userFind = res.data
console.log(Vue.prototype.$userFind)
})
}
export default api
【三】:request.js
import config from './config.js'
// 注册路由
import route from './route.js'
import Vue from 'vue'
const webUrl = config.webUrl
const request = {}
request.globalRequest = (url, params = [], method = 'GET') =>{
// 获取缓存中的token
var tokenStorage = url == route._refreshToken?uni.getStorageSync('refresh_token'):uni.getStorageSync('access_token');
if (tokenStorage) {
// 存在时
tokenStorage = 'Bearer '+tokenStorage
}
let sign = Date.parse(new Date())/1000;
// 页面加载完
const promise = new Promise((resolve, reject) => {
uni.request({
url: webUrl + url,
method,
data: params,
dataType: 'json',
header: {
'authorization': tokenStorage,
'sign': sign,
'token-type': 'USER',
// 'types':'WECHAT'
},
success: (res) => {
// 系统错误
if (!res.data.code) {
uni.showModal({
title: '提示',
content: '系统维护中,请稍后重试',
showCancel: false,
success: function (res) {
}
});
return
}
if (res.data.code == 208) {
console.log('code:401,jwt参数未传,直接跳转到登陆页面')
uni.navigateTo({
'url':'/pages/user/login'
})
return
}
if (res.data.code == 209) {
resolve(res.data)
return
}
//
if (res.data.code == 10050) {
// console.log('code:10050,jwt令牌过期,重新获取')
const url = route._refreshToken
request.globalRequest(url, [], 'POST').then((res)=>{
// 存入新的访问令牌-缓存
uni.setStorageSync('access_token', res.data.access_token);
// 刷新令牌-缓存
uni.setStorageSync('refresh_token', res.data.refresh_token);
// console.log(res.data)
})
return
}
if (res.data.code == 504) {
resolve(res.data)
return
}
if (res.data.code == 212) {
uni.showModal({
title: '提示',
content: '您的账户玖玖豆不足',
confirmText:'购买',
success: function (res) {
if (res.confirm) {
uni.navigateTo({
'url': '/pagesa/balance/add'
})
} else if (res.cancel) {
}
return
}
});
return
}
//
if (res.data.code == 400 || res.data.code==500) {
// console.log('参数错误,需要直接抛出异常内容')
uni.showModal({
title: '提示',
content: res.data.msg,
showCancel: false,
success: function (res) {
}
});
return
}
// ==============================================
if (res.data.code != 200) {
// console.log('参数错误,需要直接抛出异常内容')
uni.showModal({
title: '提示',
content: res.data.msg,
showCancel: false,
success: function (res) {
}
});
return
}
resolve(res.data)
},
fail: (err) => {
reject(err)
},
complete:function(err){
uni.hideLoading()
}
})
})
return promise
}
export default request
网友评论