import Vue from 'vue' import axios from 'axios' import store from '../store' import _ from 'lodash' import { Toast, Notify } from 'vant' import { getCookieValue } from '@/utils' const host = window.location.host const domain = host.substring(0, host.indexOf('.')) || host.substring(0, host.indexOf(':')) const request = axios.create({ withCredentials: true, baseURL: process.env.API_DOMAIN, timeout: 50000, headers: { 'Content-Type': 'application/json;charset=UTF-8' } }) let loading = null // 当前正在请求的数量 let needLoadingRequestCount = 0 // 显示loading function showLoading () { if (needLoadingRequestCount === 0 && !loading) { loading = Toast.loading({ message: '拼命获取中', forbidClick: true, duration: 0 }) } needLoadingRequestCount++ } // 隐藏loading function hideLoading () { needLoadingRequestCount-- needLoadingRequestCount = Math.max(needLoadingRequestCount, 0) // 做个保护 if (needLoadingRequestCount === 0) { // 关闭loading toHideLoading() } } // 防抖:将 300ms 间隔内的关闭 loading 便合并为一次。防止连续请求时, loading闪烁的问题。 const toHideLoading = _.debounce(() => { loading.clear() loading = null }, 300) // Add a request interceptor request.interceptors.request.use(request => { const inviteId = store.getters['common/inviteId'] const requestUrl = request.url // 因为微信开发者工具重复授权,本地开发时写死 if (/^(0|192|10|localhost)/.test(domain)) { request.headers.wechatToken = '911cfb17f5e881672fb6d9a625f00981' } else { request.headers.wechatToken = getCookieValue('fanbutingwechatToken') } request.url = requestUrl + (requestUrl.indexOf('?') > -1 ? '&' : '?') + 'nextUrl=' + encodeURIComponent(location.href) + (inviteId ? '&invite_id=' + inviteId : '') // 判断当前请求是否设置了不显示Loading if (request.showLoading) { showLoading() } return request }, error => { // 判断当前请求是否设置了不显示Loading if (loading) { hideLoading() } Notify({ type: 'warning', message: '请求超时' }) // Do something with request error return Promise.reject(error) }) // Add a response interceptor request.interceptors.response.use(response => { // Do something with response data const { code, url } = response.data if (loading) { hideLoading() } if (code === 401 && url) { Vue.cookie.delete('fanbutingwechatToken') location.replace(url) } return response.data }, (error) => { if (loading) { hideLoading() } Notify({ type: 'danger', message: '数据获取失败!' }) // Do something with response error return Promise.reject(error) }) export default request