axios 封装

import axios from "axios";
import store from "@/store";
import router from "@/router";

const service = axios.create();
//request拦截
service.interceptors.request.use(
  request => {
    let { current } = router.history;
    if (
      store.getters["userStore/getParamToken"] &&
      current.name !== "Login" &&
      request.url != "刷新接口URL"
    ) {
      //非登陆界面并且不是调用刷新接口并且本地要有token才可以加autho验证
      request.headers.Authorization = `Bearer ${
        store.getters["userStore/getParamToken"]
      }`;
    }
    return request;
  },
  error => {
    console.error(error);
    return error;
  }
);

//response拦截
service.interceptors.response.use(
  response => {
    return response;
  },
  async error => {
    try {
      if (error && error.response) {
        switch (error.response.status) {
          case 401:
            // 返回 401 清除token信息并跳转到登录页面
            let refreshToken = store.getters["userStore/getParamRefreshToken"];
            let { data } = await post(
              刷新的接口和参数
            );
            if (data.code === 200) {
              //刷新token成功后,获取新的token,覆盖旧的token,然后返回到报错的页面刷新掉
              store.commit("userStore/setParamToken", data.result.access_token);
              var backoff = new Promise(resolve => {
                resolve();
              });
              return backoff.then(r => {
                return service(error.config);
              });
            } else {
              let { current } = router.history;
              // current.meta.keepAlive = false;
              if (current.fullPath !== "/login") {
                store.commit("userStore/setBackUrl", current.fullPath);
              }
              //refreshtoken失效的话,就直接到登陆页面
              router.push("/login");
            }

            return error;
          default:
            console.error(error);
            return error;
        }
      } else {
        console.error(error);
        return error;
      }
    } catch (error) {
      console.error(error);
    }
  }
);

export async function get(
  url,
  params,
  contentType = "application/json;charset=UTF-8"
) {
  service.defaults.headers.post["Content-Type"] = contentType;
  return await service.get(url, params);
}

export async function post(
  url,
  params = null,
  contentType = "application/json;charset=UTF-8",
  onUploadProgress=()=>{}
) {
  service.defaults.headers.post["Content-Type"] = contentType;
  return await service.post(url, params,{
    onUploadProgress:onUploadProgress
  });
}

export async function put(
  url,
  params = null,
  contentType = "application/json;charset=UTF-8"
) {
  service.defaults.headers.post["Content-Type"] = contentType;
  return await service.put(url, params);
}

export async function remove(
  url,
  params = null,
  contentType = "application/json;charset=UTF-8"
) {
  service.defaults.headers.post["Content-Type"] = contentType;
  return await service.delete(url, { data: params });
}

  

posted @ 2020-06-12 17:23  洛晨随风  阅读(179)  评论(0编辑  收藏  举报