vue2+axios 请求拦截器及路由拦截器封装(笔记)

  1. axios依赖安装:npm install axios -S
  2. 新建axios文件夹-> baseUrl.js & index.js & router.js
  3. main.js 引入
//axios封装
import './axios'

 

js介绍:

baseUrl.js:

baseUrl.js 简单区分开发环境、测试环境及生产环境 ,之前有篇文章已经介绍  

https://blog.csdn.net/zuorishu/article/details/81484176

let baseUrl = '';

if (location.hostname == '***') { //正式环境
    baseUrl = '***';
} else if (location.hostname == '***') { //测试环境
    baseUrl = '***';
} else { //开发环境
    baseUrl = '/api'
}

export {
    baseUrl
}

 

index.js:

index.js  axios request 拦截器 & axios response 拦截器封装,只做了拦截器的不分封装,请求类型及方法没有处理;

import Vue from 'vue'  
import axios from 'axios'  
//import qs from 'qs'
import store from '../store'
import router from "../router";
import { baseUrl } from './baseUrl'
import { Toast } from 'mint-ui';
import './router'
Vue.prototype.$http = axios
//Vue.prototype.$qs = qs
axios.defaults.baseURL = baseUrl;
//axios.defaults.withCredentials = true; //让ajax携带cookie

//axios request 拦截器
axios.interceptors.request.use(
    config => {
        if (store.state.sessionId != '') { // 每次发送请求之前判断是否存在token,如果存在,则统一在http请求的header都加上token,不用每次请求都手动添加了
            config.headers.sessionId = store.state.sessionId;
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    }
);

//axios response 拦截器
axios.interceptors.response.use(
    response => {
        const data = response.data;
        //返回状态码处理
        switch (data.code) {
            case 0:
                return response
                break;
            case 100003:
                Toast(data.message);
                store.commit('isLogin', false);
                localStorage.removeItem('plangame')
                router.push({ path: '/login' })
                break;
            case 600003:
                Toast('请稍后刷新尝试');
                router.push({ path: '/' })
                break;
            default:
                Toast(data.message);
                return response
        }
    },
    error => {
        //请求报错处理
        switch (error.response.status) {
            case 500:
                Toast('服务端异常');
                break;
            case 400:
                Toast('请重新登陆');
                store.commit('isLogin', false);
                localStorage.removeItem('plangame')
                router.push({ path: '/login' })
                break;
            case 404:
                router.push({ path: '/error/404' })
                break;
            default:
                return Promise.reject(error)
        }
    }
)

 router.js

router.js 路由拦截器

import store from '../store'
import router from "../router";
//路由验证
router.beforeEach((to, from, next) => {
    if (to.matched.some(m => m.meta.auth)) {
        // 对路由进行验证     
        if (store.state.isLogin == true) { // 已经登陆       
            next() // 正常跳转  
        } else {
            next({ path: '/login', query: { redirect: to.fullPath } })
        }
    } else {
        next()
    }

    /*如果已登陆不允许直接跳转到 登录页面*/
    let fullPath = to.fullPath.substring(0, 6);
    if (fullPath == "/login") {
        if (store.state.isLogin == true) {
            next({
                path: from.fullPath
            });
        } else {
            next();
        }
    }
})

 

©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页