axios 拦截器处理通用封装

 

 aioxs 通用封装,比如在登录的时候,若登录给后面接口,多传个token。有助安全性。 对于 异常处理。 拦截器 ,请求前,得到资源后。

 

 aioxs封装

import axios from 'axios'
import store from '@/store/index.js'
import baseURL from './baseUrl'
import { Message } from 'element-ui'
const http = {}

var instance = axios.create({
    timeout: 5000,
    baseURL
})

// 添加请求拦截器
instance.interceptors.request.use(
    function(config) {
        // 请求头添加token
        if (store.state.UserToken) {
            config.headers.Authorization = store.state.UserToken
        }
        return config
    },
    function(error) {
        return Promise.reject(error)
    }
)

// 响应拦截器即异常处理
instance.interceptors.response.use(
    response => {
        return response.data
    },
    err => {
        if (err && err.response) {
        //状态的异常处理 switch (err.response.status) { case 400: err.message = '请求出错' break case 401: Message.warning({ message: '授权失败,请重新登录' }) store.commit('LOGIN_OUT') setTimeout(() => { window.location.reload() }, 1000) return case 403: err.message = '拒绝访问' break case 404: err.message = '请求错误,未找到该资源' break case 500: err.message = '服务器端出错' break } } else { err.message = '连接服务器失败' } Message.error({ message: err.message }) return Promise.reject(err.response) } ) http.get = function(url, options) { // get请求封装 return new Promise((resolve, reject) => { instance .get(url, options) .then(response => { if (response.code === 0) { resolve(response.data) } else { Message.error({ message: response.message }) reject(response.message) } }) .catch(e => { console.log(e) }) }) } http.post = function(url, data, options) { //post请求封装 return new Promise((resolve, reject) => { instance .post(url, data, options) .then(response => { if (response.code === 0) { resolve(response.data) } else { Message.error({ message: response.message }) reject(response.message) } }) .catch(e => { console.log(e) }) }) } export default http

  

const baseUrl = 'http://localhost:8080'
export default baseUrl

  

import Vue from 'vue'
import Vuex from 'vuex'

import state from './state'
import getters from './getters'
import modules from './modules'
import actions from './actions'
import mutations from './mutations'

Vue.use(Vuex)

export default new Vuex.Store({
    state,
    getters,
    mutations,
    actions,
    modules
})

  

项目地址  https://github.com/linrunzheng/vue-permission-control

基于vue, vue-router, vuex进行权限控制

posted @ 2019-11-12 15:19  打个大大西瓜  阅读(317)  评论(0编辑  收藏  举报