vue中建立axios拦截器

1.引入axios

npm install axios -S

2.建立拦截器

import Vue from 'vue'
import axios from 'axios'  //引入axios
import router from '@/router'  //引入router
import { Toast } from 'mint-ui';//引入ui提示组件,这个随意



//创建一个axios实例
let instance = axios.create({
    headers: {
        'content-type': 'application/x-www-form-urlencoded'
    }
})

//返回token,拿到token这里的获取逻辑按你们自己的项目来
function returnBearer(){
    let user = JSON.parse(localStorage.getItem('user'))
    let bearer = user.token_type + ' ' + user.access_token
    return bearer
}

// http request 拦截器
instance.interceptors.request.use(
    config => {
        if (localStorage.getItem('user')) { // 判断是否存在token,如果存在的话,则每个http header都加上token
            config.headers.authorization = returnBearer()  //请求头加上token
        }
        return config
    },
    err => {
        return Promise.reject(err)
    }
)

// http response 拦截器
instance.interceptors.response.use(
    response => {
        if(response){
            if(response.data.code == 401){//这里的逻辑自行修改
                router.replace({
                    path: '/',
                    query:{
                        type: "loginOut"
                    }
                })
            }else if(response.data.code == 400){
                Toast(response.data.msg)
            }else if(response.data.code == 422){
                Toast(response.data.msg)
            }else if(response.data.code == 500){
                Toast(response.data.msg)
            }
            
        }
      return response
    },
    //接口错误状态处理,也就是说无响应时的处理
    error => {
        console.log(1)
        if (error.response) {
            if(error.response.status== 401){//这里的逻辑自行修改
                router.replace({
                    path: '/',
                    query:{
                        type: "loginOut"
                    }
                })
            }else if(error.response.status == 422){
                Toast(response.data.msg)
            }else{
                Toast(response.data.msg)
            }
        }
      return Promise.reject(error.response) // 返回接口返回的错误信息
    }
)

export default instance//抛出实例,便于全局引用

3.在mian.js全局引用

import instance from '@/api/axios'//拦截器
Vue.prototype.$instance = instance

你可能感兴趣的:(vue中建立axios拦截器)