Newer
Older
HuangJiPC / src / utils / request.js
@gzy gzy on 4 Jul 1 KB update
import axios from 'axios';
import store from '@/store';

axios.defaults.withCredentials = true;

// 创建 axios 实例
const service = axios.create({
  timeout: 10000, // 请求超时时间
});

const err = (error) => {
  const { response } = error;
  if (response && response.status) {
    const { status } = response;
    window.$notification.error({
      content: `请求错误 ${status}`,
      meta: '接口错误,请联系管理员',
      duration: 2500,
    });
  } else if (!response) {
    window.$notification.error({
      content: '网络异常',
      meta: '请检查您的网络',
      duration: 2500,
    });
  }
  return response;
};
//请求拦截器
service.interceptors.request.use((config) => {
  // 鸿数将token拼接在iframe的src里面
  const token = localStorage.getItem('tokenXF');
  // const token = new URL(window.location).searchParams.get('hsTn');
  // localStorage.setItem('tokenXF', token);

  if (token) {
    config.headers['token'] = token; // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  config.headers['Content-Type'] = 'application/json';
  return config;
}, err);
// 响应拦截器
service.interceptors.response.use((response) => {
  if (response.data.code === 401) {
    window.$notification.error({
      content: '登录已过期',
      meta: '请返回重新登录了再进行操作',
      duration: 2500,
    });
    // 重置vuex里的用户信息;
    store.commit('user/RESET_INFO');
    top.window.location.href = 'http://192.168.10.33:7000/login'; //鸿数登录页
  } else if (response.data.code == 500) {
    window.$message.warning(response.data.msg || '服务器发生错误');
  }
  return response.data;
}, err);

export default service;