123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- 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 = '22aff98dec057448c59427e42065d3df'
- } 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
|