request.js 5.68 KB
Newer Older
chenwei's avatar
chenwei committed
1 2 3 4 5
import axios from "axios";
import { Notification, MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
import errorCode from "@/utils/errorCode";
lanbaoming's avatar
lanbaoming committed
6
import Cookies from "js-cookie";
chenwei's avatar
chenwei committed
7 8
import { getTenantEnable } from "@/utils/ruoyi";
import { getLocale } from "@/utils/db";
lanbaoming's avatar
lanbaoming committed
9 10 11 12 13
import i18n from "@/i18n";

// 是否显示重新登录
export let isRelogin = { show: false };

chenwei's avatar
chenwei committed
14
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
lanbaoming's avatar
lanbaoming committed
15 16 17
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项,表示请求URL公共部分
chenwei's avatar
chenwei committed
18 19 20
  baseURL:
    (localStorage.VUE_APP_BASE_API || process.env.VUE_APP_BASE_API) +
    "/admin-api/", // 此处的 /admin-api/ 地址,原因是后端的基础路径为 /admin-api/
lanbaoming's avatar
lanbaoming committed
21
  // 超时
yujinyao's avatar
yujinyao committed
22
  timeout: 1000 * 60,
chenwei's avatar
chenwei committed
23
});
lanbaoming's avatar
lanbaoming committed
24 25

// 如果是生产环境则打印提示
chenwei's avatar
chenwei committed
26 27 28 29 30 31 32 33 34 35 36 37
if (
  process.env.NODE_ENV === "development" &&
  service.defaults.baseURL === "https://api2.groupage.cn/admin-api/"
) {
  console.log(
    "%c请注意,当前为生产环境请谨慎操作!!",
    "background-color: red; font-size: 3em; color:yellow"
  );
  console.log(
    "%c接口地址:" + service.defaults.baseURL,
    "background-color: black; font-size: 1.5em; color:yellow !important"
  );
lanbaoming's avatar
lanbaoming committed
38 39 40
}

// request拦截器
chenwei's avatar
chenwei committed
41 42 43 44 45 46 47
service.interceptors.request.use(
  (config) => {
    config.headers["locale"] = getLocale();
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false;
    if (getToken() && !isToken) {
      config.headers["Authorization"] = "Bearer " + getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
lanbaoming's avatar
lanbaoming committed
48
    }
chenwei's avatar
chenwei committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
    // 设置租户
    if (getTenantEnable()) {
      const tenantId = Cookies.get("tenantId");
      if (tenantId) {
        config.headers["tenant-id"] = tenantId;
      }
    }
    // get请求映射params参数
    if (config.method === "get" && config.params) {
      let url = config.url + "?";
      for (const propName of Object.keys(config.params)) {
        const value = config.params[propName];
        var part = encodeURIComponent(propName) + "=";
        if (value !== null && typeof value !== "undefined") {
          if (typeof value === "object") {
            for (const key of Object.keys(value)) {
              let params = propName + "[" + key + "]";
              var subPart = encodeURIComponent(params) + "=";
              url += subPart + encodeURIComponent(value[key]) + "&";
            }
          } else {
            url += part + encodeURIComponent(value) + "&";
lanbaoming's avatar
lanbaoming committed
71 72 73
          }
        }
      }
chenwei's avatar
chenwei committed
74 75 76
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
lanbaoming's avatar
lanbaoming committed
77
    }
chenwei's avatar
chenwei committed
78 79 80 81 82
    return config;
  },
  (error) => {
    console.log(error);
    Promise.reject(error);
lanbaoming's avatar
lanbaoming committed
83
  }
chenwei's avatar
chenwei committed
84
);
lanbaoming's avatar
lanbaoming committed
85 86

// 响应拦截器
chenwei's avatar
chenwei committed
87 88
service.interceptors.response.use(
  (res) => {
lanbaoming's avatar
lanbaoming committed
89 90 91
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
chenwei's avatar
chenwei committed
92
    const msg = errorCode[code] || res.data.msg || errorCode["default"];
lanbaoming's avatar
lanbaoming committed
93 94 95
    if (code === 401) {
      if (!isRelogin.show) {
        isRelogin.show = true;
chenwei's avatar
chenwei committed
96 97 98 99 100 101 102
        MessageBox.confirm(
          "登录状态已过期,您可以继续留在该页面,或者重新登录",
          "系统提示",
          {
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
            type: "warning",
lanbaoming's avatar
lanbaoming committed
103
          }
chenwei's avatar
chenwei committed
104 105 106 107 108 109
        )
          .then(() => {
            isRelogin.show = false;
            store.dispatch("LogOut").then(() => {
              location.href = "/";
            });
lanbaoming's avatar
lanbaoming committed
110
          })
chenwei's avatar
chenwei committed
111 112 113
          .catch(() => {
            isRelogin.show = false;
          });
lanbaoming's avatar
lanbaoming committed
114
      }
chenwei's avatar
chenwei committed
115
      return Promise.reject("无效的会话,或者会话已过期,请重新登录。");
lanbaoming's avatar
lanbaoming committed
116 117 118 119
    } else if (code === 500) {
      Message({
        dangerouslyUseHTMLString: true,
        message: msg,
chenwei's avatar
chenwei committed
120 121 122
        type: "error",
      });
      return Promise.reject(new Error(msg));
lanbaoming's avatar
lanbaoming committed
123 124
    } else if (code === 901) {
      Message({
chenwei's avatar
chenwei committed
125
        type: "error",
lanbaoming's avatar
lanbaoming committed
126 127
        duration: 0,
        dangerouslyUseHTMLString: true,
chenwei's avatar
chenwei committed
128 129 130 131 132 133 134 135
        message:
          "<div>演示模式,无法进行写操作</div>" +
          "<div> &nbsp; </div>" +
          "<div>参考 https://doc.iocoder.cn/ 教程</div>" +
          "<div> &nbsp; </div>" +
          "<div>5 分钟搭建本地环境</div>",
      });
      return Promise.reject(new Error(msg));
lanbaoming's avatar
lanbaoming committed
136 137
    } else if (code === 555) {
      // 额外情况
chenwei's avatar
chenwei committed
138
      return Promise.reject(res.data);
lanbaoming's avatar
lanbaoming committed
139 140
    } else if (code === 566) {
      // 额外情况
chenwei's avatar
chenwei committed
141
      return Promise.reject(res.data);
lanbaoming's avatar
lanbaoming committed
142 143
    } else if (code === 666) {
      // 额外情况
chenwei's avatar
chenwei committed
144
      return Promise.reject(res.data);
lanbaoming's avatar
lanbaoming committed
145 146
    } else if (code !== 200) {
      // 如果内容很长则用alert提示,不然可能显示不全,自动隐藏也会导致看不完整就消失了
chenwei's avatar
chenwei committed
147 148 149
      if (msg.length > 300) {
        MessageBox.alert(msg, i18n.t("错误提示"), i18n.t("确定"));
      } else {
lanbaoming's avatar
lanbaoming committed
150
        Notification.error({
chenwei's avatar
chenwei committed
151 152
          title: msg,
        });
lanbaoming's avatar
lanbaoming committed
153 154
      }

chenwei's avatar
chenwei committed
155
      return Promise.reject(msg || "error");
lanbaoming's avatar
lanbaoming committed
156
    } else {
chenwei's avatar
chenwei committed
157
      return res.data;
lanbaoming's avatar
lanbaoming committed
158 159
    }
  },
chenwei's avatar
chenwei committed
160 161
  (error) => {
    console.log("err" + error);
lanbaoming's avatar
lanbaoming committed
162 163 164
    let { message } = error;
    if (message === "Network Error") {
      message = "后端接口连接异常";
chenwei's avatar
chenwei committed
165
    } else if (message.includes("timeout")) {
lanbaoming's avatar
lanbaoming committed
166
      message = "系统接口请求超时";
chenwei's avatar
chenwei committed
167
    } else if (message.includes("Request failed with status code")) {
lanbaoming's avatar
lanbaoming committed
168 169 170 171
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message({
      message: message,
chenwei's avatar
chenwei committed
172 173 174 175
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
lanbaoming's avatar
lanbaoming committed
176
  }
chenwei's avatar
chenwei committed
177
);
lanbaoming's avatar
lanbaoming committed
178 179 180

export function getBaseHeader() {
  return {
chenwei's avatar
chenwei committed
181 182 183
    Authorization: "Bearer " + getToken(),
    "tenant-id": Cookies.get("tenantId"),
  };
lanbaoming's avatar
lanbaoming committed
184 185
}

chenwei's avatar
chenwei committed
186
export default service;