1、封装request.js请求
封装的过程中,可以根据自己的项目需求,在请求接口添加一些loading和后端返回的状态码做判断处理。
export default {
common: {
baseUrl:https://xxxxx,//请求数据的域名
data: {},
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: 'GET',
dataType: 'json',
},
request(options = {}) {
// 判断是自带基础的请求
options.url = options.baseUrl + options.url
options.data = options.data || this.common.data;
options.header = options.header || this.common.header;
options.dataType = options.dataType || this.common.dataType;
return new Promise((resolve, reject) => {
if (options.isShowLoading) {
uni.showLoading({
title: '加载中...',
})
}
uni.request({
...options,
success: (res) => {
// console.log('res',res)
if (res.statusCode && res.statusCode != 200) {
common.showToast("api错误:错误码" + res.statusCode, 'none', 3000)
return;
}
if (res.data.error_code != 0) {
if (res.data.error_code = 70006) {
console.error(res.data.error)
} else {
setTimeout(() => {
common.showToast(res.data.error, 'none', 3000)
}, 100)
console.error(res.data.error)
}
}
resolve(res.data);
},
fail: (err) => {
reject(err.data)
},
complete: (res) => {
if (options.isShowLoading) {
uni.hideLoading();
}
}
})
})
}
}
2、新建一个api.js文件,分类存放我们的接口请求
import http from '@/utlis/request.js'
const request=http.request;
// 获取用户usercode信息
export function GetUser(data){
return http.request({
url:'/WxUser/OnLogin',
data:data,
method:'POST',
isShowLoading:false
})
}
// 更新用户头像昵称具体信息
export function UpdateInfo(data){
return http.request({
url:'/WxUser/UpdateInfo',
data:data,
method:'POST',
isShowLoading:true
})
}
3、在页面导入以及使用
import {UpdateInfo} from '@/api/login.js'
//更新用户信息
async updateUserInfo(userInfo, WXUserInfo) {
if (userInfo && WXUserInfo) {
var params = {
isNewUser: userInfo.isNewUser,
usercode: userInfo.usercode,
encryptedData: WXUserInfo.encryptedData,
};
let {data,error_code,error} = await UpdateInfo(params);
if(error_code===0){
let temp = Object.assign(app.globalData.userInfo,data);
uni.setStorageSync('userInfo', temp);
app.globalData.userInfo = temp;
app.globalData.isLogin = true;
this.show=false
// 返回上一页
uni.navigateBack({
delta: 1
});
}else{
uni.removeStorageSync('WXUserInfo')
uni.showToast({
title: "错误" + error,
icon: 'none',
});
}
}
},