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
- function showLoading () {
- if (needLoadingRequestCount === 0 && !loading) {
- loading = Toast.loading({
- message: '拼命获取中',
- forbidClick: true,
- duration: 0
- })
- }
- needLoadingRequestCount++
- }
- function hideLoading () {
- needLoadingRequestCount--
- needLoadingRequestCount = Math.max(needLoadingRequestCount, 0)
- if (needLoadingRequestCount === 0) {
-
- toHideLoading()
- }
- }
- const toHideLoading = _.debounce(() => {
- loading.clear()
- loading = null
- }, 300)
- 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 : '')
-
- if (request.showLoading) {
- showLoading()
- }
- return request
- }, error => {
-
- if (loading) {
- hideLoading()
- }
- Notify({
- type: 'warning',
- message: '请求超时'
- })
-
- return Promise.reject(error)
- })
- request.interceptors.response.use(response => {
-
- 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: '数据获取失败!'
- })
-
- return Promise.reject(error)
- })
- export default request
|