Vue-axios封装

/*
 * @Description: axios封装
 * @Author: 刘
 * @email: [email protected]
 * @Date: 2021-02-04 11:32:45
 * @LastEditTime: 2021-02-25 19:10:24
 */
import axios from "axios";
import router from "../router/index";
import NProgress from 'nprogress'
import {
  Message
} from "element-ui"
import {
  time
} from "echarts";
var baseURL = "/api";
const service = axios.create({
  baseURL,
  timeout: 1 * 1000,
});
const toLogin = () => {
  router.push({
    path: "/login",
    query: {
      // 把当前的路由传递过去 这样我们登陆成功之后就可以从哪里来返回到哪里去
      backRouter: router.currentRoute.fullPath,
    },
  });
};
service.interceptors.request.use((config) => {
  NProgress.start();
  if (localStorage.getItem('token')) {
    config.headers.Authorization = localStorage.getItem('token')
  }
  return config;
}, (error) => {
  console.log(error)
  return Promise.reject(error);
});
service.interceptors.response.use((config) => {
  NProgress.done();

  if (config.status == 200) {
    return config.data;
  } else {
    console.log("请求失败", config);
  }
}, error => {
  let index = error.message.indexOf('timeout');
  if (index > -1) {
    return Promise.reject('请求超时了,请重试!')
  }
  let statusCode = error.response.status;
  if (statusCode) {
    switch (statusCode) {
      case 401:
        Message({
          type: 'error',
          message: "暂无权限,请先登陆哦!"
        })
        toLogin();
        break;
      case 403:
        Message({
          type: 'error',
          message: "登陆过期,请重新登陆!"
        })
        localStorage.removeItem("token");
        toLogin();
      case 500:
        Message({
          type: 'error',
          message: "服务器异常!"
        })
      default:
        console.log(error.code)
        break;
    }
  }

})

export default service;

你可能感兴趣的:(Vue-axios封装)