ai-watch-app/config/request.js

106 lines
2.4 KiB
JavaScript

import store from "../store/index.js";
import utils from "../utils/utils.js";
import { baseUrl } from "./api.js";
const HOST = location && location.origin
export default () => {
// 初始化请求配置
uni.$u.http.setConfig((config) => {
// #ifdef APP-PLUS
config.baseURL = baseUrl; // 测试地址
// #endif
return config
});
// 请求拦截
uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
config.data = config.data || {};
// config.baseURL = 'http://test.sc2.agrimedia.cn'; // 不使用请求代理 上线记得注释掉 ***********************************************************
let apiToken = store.getters['api/getApiToken']
let serverTime = (parseInt(Date.now() /1000) - store.getters['api/getServerTime'])
config.header.systemType = 0;
config.header.ApiToken = apiToken
config.header.timestamp = serverTime
let ob = (config.method == 'GET'? config.params : config.data)
uni.showLoading({
mask: true,
title:"加载中..."
});
return config
}, config => { // 可使用async await 做异步操作
return Promise.reject(config)
})
// 响应拦截
uni.$u.http.interceptors.response.use((response) => {
uni.hideLoading({});
/* 对响应成功做点什么 可使用async await 做异步操作*/
const data = response.data
const custom = response.config?.custom
if (data.code !== 200) {
if (data.code === 401 || data.code === 1005) {
uni.showToast({
mask: true,
title:data.msg,
icon:'none'
});
// setTimeout(e => {
// utils.goPath('/pages/login/login');
// },1000)
} else if (data.code === 400) {
uni.showToast({
mask: true,
title: data.msg,
icon: 'none'
})
} else if (data.code === 0) {
uni.showToast({
mask: true,
title: data.msg,
icon: 'none'
})
}
if (custom.toast !== false) {
uni.$u.toast(data.msg)
}
if (data.code == 1005) {
uni.showToast({
mask: true,
title: '请重新登录',
icon: 'none'
})
setTimeout(() => {
uni.reLaunch({
url: '/pages/login/login'
})
}, 1000)
}
console.log(response.config.url)
return Promise.reject(data)
}
return data.data === undefined ? {} : data.data;
}, (response) => {
uni.showToast({
mask: true,
title: '服务器响应失败' + response.statusCode,
icon: 'none'
})
return Promise.reject(response)
})
}