目录
1、request.js文件
function request({
url,
method,
isAuth,
data,
isShowLoading = true
}) {
return new Promise((resolve, reject) => {
let header = {}
if (isAuth) {
let access_token = uni.getStorageSync('access_token')
if (!access_token) {
uni.navigateTo({
url: '/pages/auth/auth'
})
return
}
if (method == 'POST') {
header = {
'Authorization': 'Bearer ' + access_token,
'Content-Type': 'application/x-www-form-urlencoded'
}
} else if (method == 'GET') {
header = {
'Authorization': 'Bearer ' + access_token
}
}
}
// 请求前开启loading
if (isShowLoading) {
uni.showLoading({
title: '加载中',
mask: true
})
}
uni.request({
url: url,
method,
header,
data: data,
complete: res => {
let {
statusCode
} = res
// 请求后关闭loading
if (isShowLoading) {
uni.hideLoading()
}
if (statusCode === 401) {
uni.removeStorageSync('access_token')
// 跳转登录页面
uni.navigateTo({
url: '/pages/auth/auth'
})
} else if (statusCode === 200) {
// 请求成功后
resolve(res.data)
} else if (statusCode === 404) {
// 跳转4XX页面
uni.navigateTo({
url: '/pages/error/4XX/4XX'
})
} else if (statusCode === 501 || statusCode === 502 || statusCode === 503) {
// 跳转5XX页面
uni.navigateTo({
url: '/pages/error/5XX/5XX'
})
} else {
reject(res)
}
}
})
})
}
export default request
2、main.js全局挂载
import Vue from 'vue';
import App from './App';
import request from '@/common/request.js';
Vue.config.productionTip = false;
// 挂载全局函数
Vue.prototype.$request = request;
App.mpType = 'app';
const app = new Vue({
...App,
});
app.$mount();
3、页面中使用
this.$request({
url: this.BASE_URL + '/api/xxx/detail',
method: 'GET',
isAuth: true,
data: {
id: id
}
})
.then(res => {
this.detail = res.detail;
})
.catch(res => {
uni.showToast({
icon: 'none',
title: res.data.error_msg,
duration: 3000
});
});
最新回复