Vue

配置项目中的axios拦截器

2019-09-30  本文已影响0人  Issho

☼ 注:笔者的文章是根据自己当前项目做的笔记,具体应用请参照自己实际项目情况

import axios from 'axios'
import qs from 'qs'
import rootStore from '@/store'
import { message } from 'antd'
import { HOST } from '../config'
import React from 'react'
import ReactDOM from 'react-dom'
import Cache from '@/utils/Cache'
import CheckLoginStatus from '@/components/check-login'
import { HashRouter as Router } from 'react-router-dom'

let loading, warn

// 暂时的简单配置,等联调接口时,做一些细节处理
const Axios = axios.create({
    baseURL: HOST, // 前缀:window.location.origin
    responseType: 'json', // 数据格式
    withCredentials: true, // 是否允许带cookie
    headers: {
        'Content-Type': 'application/json;charset=UTF-8' // json格式数据
    }
})

// http请求拦截器<pending>
Axios.interceptors.request.use(
    config => {
        if (!loading) {
            loading = message.loading('', 0)
        }
        if (config.method === 'post') {
            if (config.data && config.data.headers) { // 针对post的处理
                config.headers = config.data.headers
            }
            if (config.data.responseType) {
                config.responseType = config.data.responseType
            }

            config.data = config.headers['Content-Type'] === 'application/x-www-form-urlencoded' ?qs.stringify(config.data.param) : config.data.param
        } else { // get
            config.params = config.param
        }
        // 取消请求
        config.cancelToken = rootStore.Root.source.token

        return config
    },
    error => { // 响应错误处理
        if (!warn) {
            warn = message.warning('调用失败,稍后请重试', 1)
            warn = null
        }
        setTimeout(loading, 0)
        return Promise.reject(error)
    }
)

// http响应拦截器<done>
Axios.interceptors.response.use(
    response => {
        // 针对请求成功的处理
        if (response && response.data && +response.data.code === 0) {
            setTimeout(loading, 0)
            return response.data
        }

        // 针对后台返回blob的处理
        if (response && (response.config.responseType === 'blob')) {
            setTimeout(loading, 0)
            // 针对后台返回的JSON格式的错误信息
            if (response.data && response.data.type === 'application/json') {
                let reader = new FileReader()
                reader.onload = e => message.info(JSON.parse(e.target.result).msg)
                reader.readAsText(response.data)
                return
            }
            // 需要针对IE做兼容,所以直接返回blob对象,再针对不同浏览器做url转化处理
            // return window.URL.createObjectURL(new Blob([response.data], { type: response.data.type }))
            return new Blob([response.data], { type: response.data.type })
        }

        // 针对后台返回用户未登录的状态(路由重定向到登录页)
        if (response && response.data && +response.data.code === 100010110) {
            // 清空本地缓存
            Cache.clear()
            const div = document.createElement('div')
            ReactDOM.render(<Router><CheckLoginStatus/></Router>, div)
            ReactDOM.unmountComponentAtNode(div)
            return
        }

        // 针对code非0的处理
        response.data && message.info(response.data.msg)
        setTimeout(loading, 0)
        // return response
    },
    error => { // 响应错误处理
        if (!error.response) {
            setTimeout(loading, 0)
            return Promise.reject(error)
        }
        if (!warn) {
            warn = message.warning('调用失败,稍后请重试', 1)
            warn = null
        }
        setTimeout(loading, 0)
        return Promise.reject(error)
    }
)

export default Axios
上一篇 下一篇

猜你喜欢

热点阅读