http.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import Vue from 'vue';
  2. import axios from 'axios';
  3. import router from '@/router';
  4. import { Message } from 'element-ui';
  5. const httpPlugin = {
  6. install(Vue, options) {
  7. // console.log(options);
  8. // 1 添加 全局方法 $http 用来发送网络请求;使用方式 Vue.$http()
  9. // 2 添加 实例方法 $http 用来实现 通过组件实例 发起网络请求;使用方式 在组件内部 this.$http()
  10. const axiosInstance = axios.create(options);
  11. // 给Axios实例 拦截器
  12. axiosInstance.interceptors.request.use(
  13. function (config) {
  14. // 在发送请求之前做些什么
  15. // 给 所有请求 添加一个 名为 Authorization的请求头,值为 Bearer + 空格 + token
  16. let token = sessionStorage.getItem('token');
  17. if (token) {
  18. config.headers['Authorization'] = `Bearer ${token}`;
  19. }
  20. return config;
  21. },
  22. function (error) {
  23. // 对请求错误做些什么
  24. return Promise.reject(error);
  25. }
  26. );
  27. // 添加响应拦截器
  28. axiosInstance.interceptors.response.use(
  29. function (response) {
  30. // 2xx 范围内的状态码都会触发该函数。
  31. // 2 如果 token在请求过程中 已经过期了,页面需要重新登录 并且 告知用户
  32. if (response.data.code === 401) {
  33. Message({
  34. message: '您未登录或登录已过期,请重新登录!',
  35. type: 'warning',
  36. showClose: true,
  37. duration: 1500,
  38. });
  39. setTimeout(() => {
  40. router.push({ name: 'login' });
  41. }, 500);
  42. }
  43. // 1. 如果请求成功了,我们直接将后台服务器响应的数据返回,不再返回axios固定的结构数据
  44. // 对响应数据做点什么
  45. return response.data;
  46. },
  47. function (error) {
  48. // 超出 2xx 范围的状态码都会触发该函数。
  49. // 对响应错误做点什么
  50. return Promise.reject(error);
  51. }
  52. );
  53. Vue.$http = Vue.prototype.$http = axiosInstance;
  54. },
  55. };
  56. Vue.use(httpPlugin, {
  57. baseURL: '/api/v1',
  58. timeout: 1000,
  59. });