import Vue from 'vue'; import axios from 'axios'; import router from '@/router'; import { Message } from 'element-ui'; const httpPlugin = { install(Vue, options) { // console.log(options); // 1 添加 全局方法 $http 用来发送网络请求;使用方式 Vue.$http() // 2 添加 实例方法 $http 用来实现 通过组件实例 发起网络请求;使用方式 在组件内部 this.$http() const axiosInstance = axios.create(options); // 给Axios实例 拦截器 axiosInstance.interceptors.request.use( function (config) { // 在发送请求之前做些什么 // 给 所有请求 添加一个 名为 Authorization的请求头,值为 Bearer + 空格 + token let token = sessionStorage.getItem('token'); if (token) { config.headers['Authorization'] = `Bearer ${token}`; } return config; }, function (error) { // 对请求错误做些什么 return Promise.reject(error); } ); // 添加响应拦截器 axiosInstance.interceptors.response.use( function (response) { // 2xx 范围内的状态码都会触发该函数。 // 2 如果 token在请求过程中 已经过期了,页面需要重新登录 并且 告知用户 if (response.data.code === 401) { Message({ message: '您未登录或登录已过期,请重新登录!', type: 'warning', showClose: true, duration: 1500, }); setTimeout(() => { router.push({ name: 'login' }); }, 500); } // 1. 如果请求成功了,我们直接将后台服务器响应的数据返回,不再返回axios固定的结构数据 // 对响应数据做点什么 return response.data; }, function (error) { // 超出 2xx 范围的状态码都会触发该函数。 // 对响应错误做点什么 return Promise.reject(error); } ); Vue.$http = Vue.prototype.$http = axiosInstance; }, }; Vue.use(httpPlugin, { baseURL: '/api/v1', timeout: 1000, });