12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- import axios from "axios";
- import { getCookie } from "@/utills/auth";
- import BASE from "@tools/basicTool.js";
- import store from "@/store";
- import route from "@/router";
- import { ElMessageBox, ElMessage } from "element-plus";
- // import { getToken } from "@/utils/storage";
- const service = axios.create();
- service.defaults.timeout = 50000;
- service.defaults.baseURL = `${process.env.VUE_APP_API}`;
- service.interceptors.request.use(
- (config) => {
- const t = (config.headers || {}).isToken;
- const u = (config.headers || {}).isUser;
- const isToken = t === false || t === "false";
- if (!isToken) {
- // // 让请求携带自定义token 请根据实际情况自行修改
- if (u) {
- config.headers["Authorization"] = "Bearer " + getCookie("authToken");
- } else {
- config.headers["token"] = getCookie("authToken");
- config.headers["userId"] = getCookie("userId");
- }
- }
- // 统一格式包装请求参数
- if (config.showLoading) {
- BASE.showLoading();
- service.defaults.showLoading = config.showLoading;
- }
- return config;
- },
- (error) => {
- return Promise.reject(error);
- }
- );
- service.interceptors.response.use(
- // Loading.close(),
- (response) => {
- const code = response.data.code;
- if (code == 401) {
- ElMessageBox.alert(
- "登录状态已过期,您可以继续留在该页面,或者重新登录",
- "系统提示",
- {
- confirmButtonText: "重新登录",
- cancelButtonText: "取消",
- type: "warning",
- callback: () => {
- store.dispatch("user/LogOut").then(() => {
- route.push("/home");
- });
- },
- }
- );
- } else {
- // 处理正常返回数据
- const { status } = response;
- if (service.defaults.showLoading) {
- BASE.closeLoading();
- service.defaults.showLoading = false;
- }
- if (status === 200) {
- console.log(response.data);
- return response.data;
- } else {
- return false;
- }
- }
- },
- (error) => {
- // 处理错误并给出相应的错误处理
- if (error.response) {
- console.log(error);
- // const { status } = error.response;
- // tips[status](error);
- return error.response.data;
- } else {
- return false;
- }
- }
- );
- export default service;
|