ty-mobile-uni
Version:
uView UI,是uni-app生态优秀的UI框架,全面的组件和便捷的工具会让您信手拈来,如鱼得水
66 lines (60 loc) • 1.76 kB
JavaScript
import Vue from 'vue';
import uni_request from './uni_request.js';
import { getToken } from "./auth.js";
import { showFullScreenLoading, tryHideFullScreenLoading } from "./loading";
const request = uni_request({
timeout: 10000, // 超时时间
header: {
'x-custom-header': 'x-custom-header'
}, // 设置请求头,建议放在请求拦截器中
statusCode: [200, 401] // 服务器相应状态码为 200/401 时,网络请求不会 reject
})
// 请求失败统一处理方法
request.onerror = async (...args) => {
//console.log('网络请求失败了', `url为${args[1]}`)
tryHideFullScreenLoading();
}
//请求拦截器
request.interceptors.request.use((config, ...args) => {
var token = getToken();
if (token) {
config.header.Authorization = token;
}
if (!config.hideLoading) {
//全局加载
showFullScreenLoading();
}
return config
}, (error) => {
tryHideFullScreenLoading();
return Promise.reject(error);
})
//响应拦截器
request.interceptors.response.use((response, ...args) => { // 响应拦截器
//关闭loading
tryHideFullScreenLoading();
var info = (typeof response.data === 'string') ? JSON.parse(response.data):response.data;
if (info.code == '200') {
return info;
} else if (info.code == '401') {
if(Vue.prototype.tokenInvalidCallback){
Vue.prototype.tokenInvalidCallback();
}
uni.showToast({
icon: 'none',
title: '请重新登录!',
duration: 2000
});
} else {
uni.showToast({
icon: 'none',
title: info.msg || '请求异常!',
duration: 2000
});
}
return Promise.reject(info);
}, (error) => {
tryHideFullScreenLoading();
return Promise.reject(error);
})
export default request;