fetch.js 1.87 KB
/**
 * 基础请求方法
 */

import axios from 'axios'
import { showFailToast, showLoadingToast } from 'vant'

const baseAxios = axios.create({
    baseURL: '',
    timeout: 20000,
})

// 加载标志计数
let loadingList = 0
let loadingToast = null
let errorMark = 0

export function fetchBase({
    url = '',
    // 需要携带在url上的参数
    params,
    // 请求体body的参数
    body = {},
    method = 'POST',
    contentType = 'json',
    loading = false
} = {}) {
    contentType === 'form' && (contentType = 'application/x-www-form-urlencoded')
    contentType === 'json' && (contentType = 'application/json; charset=utf-8')
    contentType === 'file' && (contentType = 'multipart/form-data')

    return new Promise((resolve, reject) => {
        if (loading) {
            loadingList++
            loadingToast = showLoadingToast({ message: '请求中', forbidClick: true, duration: 0 })
        }
        baseAxios({
            method: method,
            url: `${url}`,
            params: params,
            data: body,
            headers: {
                'Content-Type': contentType
            }
        }).then(function (response) {
            const data = response.data || {}
            if (data.code !== 'SUCCESS') {
                errorMark++
                reject(data)
                return
            }
            resolve(data)
        }).catch(function (err) {
            errorMark++
            reject(err)
        }).finally(() => {
            if (loading) {
                loadingList--
                if (loadingList <= 0 && loadingToast) {
                    loadingToast.close()
                    loadingToast = null
                }
            }
            if (errorMark) {
                setTimeout(() => {
                    showFailToast('请求失败')
                }, 300)
                errorMark = 0
            }
        })
    })
}