request.js 3 KB
import axios from 'axios'
import qs from 'qs'
import * as Cookies from 'js-cookie'
import router from '@/router'
import {
    loading,
    Message
} from 'element-ui'

// 创建 axios 的一个实例
const service = axios.create({
    baseURL: window._vionConfig.apiUrl, // 因为我本地做了反向代理
    timeout: 0,
    // responseType: "json",
    // changeOrigin: true,//允许跨域
    withCredentials: true, // 是否允许带cookie这些
    headers: {
        "Content-Type": "application/json;charset=UTF-8"
        // 'Content-Type': 'application/x-www-form-urlencoded'
    }
})
window.axios = service;
var loadingStatus;
let store = {
    source: {
        token: null,
        cancel: null
  }
}
// 请求拦截器
service.interceptors.request.use(
    config => {
        let language = localStorage.getItem('lang')
            , aToken = Cookies.get('atoken');
        if(language) {
            let languageObj = {
                'mall_CN': 'zh-CN,zh;q=0.9',
                'zh_CN': 'zh-CN,zh;q=0.9',
                'en_US': 'en-US,en;q=0.5',
                'zh_TW': 'zh-TW,zh;q=0.3'
            }
            languageObj[language] && (config.headers['Accept-Language'] = languageObj[language]);
        }
        aToken && (config.headers.Authorization = aToken);
        config.cancelToken = store.source.token
        return config;
    }, error => {
        Message({
            showClose: true,
            message: error,
            type: 'error.data.error.message'
        })
        return Promise.reject(error.data.msg)
    }
)

// 跳转路由打断请求
router.beforeEach((to, from, next) => {
    let CancelToken = axios.CancelTokenm
    store.source.cancel && store.source.cancel()
    store.source = CancelToken.source()
    next()
})

// 响应拦截器
service.interceptors.response.use(
    res => {
        if(res.data && !res.data.success) {
            if(res.data.ecode && res.data.ecode != 200) {
                let cookieInfo = Cookies.get()
                for(let k in cookieInfo) {
                    Cookies.remove(k)
                }
                router.push({
                    path: '/'
                })
                Message({
                    showClose: true,
                    message: res.data.enote,
                    type: 'error'
                })
                return
            } else {
                // 非标准返回体
                if(res.status == 200) {
                    return res;
                }
            }
            if(res.data.code == 500) {
                Message({
                    showClose: true,
                    message: res.data.msg,
                    type: 'error'
                })
            }
            return Promise.reject(res.data.msg);
        } else if(!res.data && res.status == 200) {
            return res;
        } else if(res.data.success && res.config.method != 'get') {
            // 
        }
        return res;
    }
    // , error => {
    //     return Promise.reject(error)
    // }
)

export default service;