import axios from "axios"; import Cookies from "js-cookie"; import NProgress from "nprogress"; import { Message } from "element-ui"; import router from "@/router/index"; import store from "@/store"; import conf from "../config/index"; // 路径配置 // axios默认配置 const service = axios.create({ baseURL: conf.baseURL, // api的base_url timeout: 600000000000000, // 请求超时时间 withCredentials: true, }); // http request 拦截器 service.interceptors.request.use( (config) => { NProgress.start(); config.headers["Content-Type"] = "application/json;charset=UTF-8"; const source = axios.CancelToken.source(); store.commit("setTokenSources", [source.token, source.cancel]); config.cancelToken = source.token; // if (Cookies.get("access_token")) { // config.headers.Authorization = "Bearer" + Cookies.get("access_token") // } return config; }, (error) => { return Promise.reject(error.response); } ); // http response 拦截器 service.interceptors.response.use( (response) => { const res = response.data; NProgress.done(); if (response.config.cancelToken) { store.commit("delTokenSources", response.config.cancelToken); } if (response.status == 200) { // Cookies.set("access_token", response.data.message, { expires: 1 / 12 }) // console.log(response.status) if (res.status == 999) { if (!location.href.includes("localhost")) { if (res.data) { window.location.href = res.data; } else { router.push({ path: "/login" }); if (res.message.includes("不存在")) { Message({ message: res.message, type: "error", duration: 3 * 1000, }); } } } return } else { // Cookies.set("access_token", response.data.message, { expires: 1 / 12 }) } } return Promise.resolve(res); }, (error) => { const { data, status } = error.response; if (error.response == undefined) { return Promise.reject(error); } if (status === 403 || status === 401) { if (data.status === 999) { console.log(data.data) if (data.data) { window.location.href = data.data; } else { Message({ message: data.info, type: "error", duration: 3 * 1000, }); router.push({ path: "/login" }); } return } Message.closeAll(); Message({ message: data.info || "未登录或登录超时,即将跳转到登录页面", type: "error", duration: 3 * 1000, }); if (!window.location.href.includes("login")) { router.push({ path: "/login", query: { url: window.location.href, }, }); } return; } Message({ message: data.info || error, type: "error", duration: 3 * 1000, }); return Promise.reject(error.response); // 返回接口返回的错误信息 } ); export default service;