110 lines
2.5 KiB
JavaScript
110 lines
2.5 KiB
JavaScript
import store from '../store'
|
|
import setting from '@/setting.js';
|
|
let timer
|
|
|
|
export default vm => {
|
|
// 初始化请求配置
|
|
uni.$u.http.setConfig((config) => {
|
|
/* config 为默认全局配置*/
|
|
config.timeout = 5000
|
|
config.baseURL = setting.fetchUrl;
|
|
return config
|
|
})
|
|
|
|
// 请求拦截
|
|
uni.$u.http.interceptors.request.use(config => {
|
|
const token = store.state.user.token
|
|
if (token) {
|
|
config.header.Authorization = 'Bearer ' + token
|
|
}
|
|
return config
|
|
}, config => {
|
|
return Promise.reject(config)
|
|
})
|
|
|
|
// 响应拦截
|
|
uni.$u.http.interceptors.response.use(response => {
|
|
const res = response.data || response
|
|
const code = res.code || res.statusCode
|
|
const { msg } = res
|
|
|
|
if (code === 401) { // token 失效
|
|
if (!timer) {
|
|
uni.showToast({
|
|
icon: 'none',
|
|
title: '用户信息已失效,请重新登录',
|
|
position: 'bottom'
|
|
})
|
|
timer = setTimeout(async () => {
|
|
try {
|
|
await store.dispatch('userFadeOut')
|
|
}
|
|
finally {
|
|
uni.$u.route({
|
|
type: 'reLaunch',
|
|
url: 'pages/login/index'
|
|
})
|
|
timer = null
|
|
}
|
|
}, 1500)
|
|
}
|
|
return Promise.reject('401 error')
|
|
}
|
|
|
|
if (code === 403) {
|
|
const errMsg = '无授权,请联系管理员'
|
|
uni.showToast({
|
|
icon: 'none',
|
|
title: errMsg,
|
|
position: 'bottom'
|
|
})
|
|
return Promise.reject(errMsg)
|
|
}
|
|
|
|
if (code !== 200) {
|
|
const errMsg = msg || 'unknown exception'
|
|
uni.showToast({
|
|
icon: 'none',
|
|
title: errMsg,
|
|
position: 'bottom'
|
|
})
|
|
return Promise.reject(errMsg)
|
|
}
|
|
return res
|
|
}, response => {
|
|
// const res = response.data || response
|
|
// const code = res.code || res.statusCode ||res.status
|
|
// const { msg } = res
|
|
// console.log(response);
|
|
let { errMsg } = response;
|
|
if (errMsg == "Network Error") {
|
|
errMsg = "后端接口连接异常";
|
|
}
|
|
else if (errMsg.includes("timeout")) {
|
|
errMsg = "系统接口请求超时";
|
|
}
|
|
else if (errMsg.includes("Request failed with status code")) {
|
|
errMsg = "系统接口" + errMsg.substr(errMsg.length - 3) + "异常";
|
|
}
|
|
uni.showToast({
|
|
icon: 'none',
|
|
title: errMsg,
|
|
position: 'bottom'
|
|
})
|
|
return Promise.reject(response)
|
|
// if(code === 403){
|
|
// uni.showToast({
|
|
// icon: 'none',
|
|
// title: '重复登录',
|
|
// position: 'bottom'
|
|
// })
|
|
// }else{
|
|
// uni.showToast({
|
|
// icon: 'none',
|
|
// title: 'unknown exception',
|
|
// position: 'bottom'
|
|
// })
|
|
// }
|
|
// return Promise.reject(response)
|
|
})
|
|
} |