12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- import store from '@/common/store/index.js'
- module.exports = (vm) => {
- // 环境判断
- uni.$u.http.setConfig((config) => {
- /* config 为默认全局配置*/
- config.header = {
- 'Content-Type': 'application/x-www-form-urlencoded',
- 'Access-Control-Allow-Headers': '*'
- }
- config.baseURL = vm.$BASE_URL; /* 根域名 */
- // config.baseURL = vm.$LAWYER_URL; /* 根域名 */
- config.withCredentials = true;
- return config
- })
- // 请求拦截部分,如配置,每次请求前都会执行
- uni.$u.http.interceptors.request.use(async (config) => {
- // 引用token
- let token = uni.getStorageSync('token');
- if(config.custom&&config.custom.auth&&!token){
- uni.$u.toast('请登录后再操作')
- setTimeout(()=>{
- vm.$Router.push('/pages/login/login')
- },1000)
- return new Promise(() => { })
- }
- if(config.custom&&config.custom.timeout){
- config.timeout = config.custom.timeout
- }
- if(config.method === 'GET'){
- config.header = {
- 'Content-Type': 'application/json;charset=UTF-8',
- }
- }else{
- config.header = {
- 'Content-Type': 'application/json;charset=UTF-8',
- }
- }
- if(config.url.includes('structured-law')){
- // config.baseURL = vm.$LAWYER_URL_FG
- config.header = {
- 'Content-Type': 'application/x-www-form-urlencoded',
- }
- }
- let data = config.method==="GET" ? config.params : config.data;
- if(token) {
- config.header['x-access-token'] = token
- }
- return config;
- }, config => { // 可使用async await 做异步操作
- return Promise.reject(config)
- })
- // 响应拦截,如配置,每次请求结束都会执行本方法
- uni.$u.http.interceptors.response.use(async (response) => {
- const data = response.data;
- const custom = response.config.custom;
- if (data.code <= 0) {
- uni.hideLoading()
- if (!custom.toast) {
- uni.$u.toast(data.msg);
- console.log(custom)
- }
- // 如果需要catch返回,则进行reject
- if (custom?.catch) {
- return Promise.reject(data)
- } else {
- // 否则返回一个pending中的promise,请求不会进入catch中
- return new Promise(() => { })
- }
- }
- return !data ? {} : data;
- },async (response) => {
- console.log(response)
- uni.hideLoading()
- /* 对响应错误做点什么 (statusCode !== 200)*/
- if (response.statusCode == 401) {
- uni.$u.toast('登录已过期,请重新登录')
- store.dispatch('userLogout')
- }else if (response.statusCode == 500) {
- uni.$u.toast('网络开了点小差,请重试');
- } else if (response.statusCode == 404) {
- return;
- } else {
- uni.$u.toast(response.data.msg);
- }
- return new Promise(() => { });
- })
- }
|