request.js 5.18 KB
Newer Older
duanledexianxianxian's avatar
duanledexianxianxian committed
1
import { notification } from 'antd';
duanledexianxianxian's avatar
duanledexianxianxian committed
2
import router from 'umi/router';
duanledexianxianxian's avatar
duanledexianxianxian committed
3 4
import HttpRequest from './kim-request';
import config from '@/config';
duanledexianxianxian's avatar
duanledexianxianxian committed
5
import store from '@/utils/store';
duanledexianxianxian's avatar
duanledexianxianxian committed
6
import { clearLoginStatus } from '@/utils/utils';
duanledexianxianxian's avatar
duanledexianxianxian committed
7

duanledexianxianxian's avatar
sync  
duanledexianxianxian committed
8 9 10 11
/**
 * todo  还需处理国际化
 */

duanledexianxianxian's avatar
duanledexianxianxian committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队(异步任务)。',
  204: '删除数据成功。',
  400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限(令牌、用户名、密码错误)。',
  403: '用户得到授权,但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除,且不会再得到的。',
  422: '当创建一个对象时,发生一个验证错误。',
  500: '服务器发生错误,请检查服务器。',
  502: '网关错误。',
  503: '服务不可用,服务器暂时过载或维护。',
  504: '网关超时。',
};
duanledexianxianxian's avatar
duanledexianxianxian committed
29
const {
duanledexianxianxian's avatar
duanledexianxianxian committed
30 31 32 33 34 35 36
  request: {
    baseUrl,
    apiPrefix,
    resCodeKey,
    resMessageKey,
    successCode,
    isThrowError = true,
duanledexianxianxian's avatar
duanledexianxianxian committed
37
    authCodes = ['system.authc'],
duanledexianxianxian's avatar
duanledexianxianxian committed
38
  },
duanledexianxianxian's avatar
duanledexianxianxian committed
39
} = config;
duanledexianxianxian's avatar
duanledexianxianxian committed
40

duanledexianxianxian's avatar
duanledexianxianxian committed
41 42 43 44 45
/**
 * 组装url
 * @param {url} url
 * @param {配置参数} more
 */
duanledexianxianxian's avatar
duanledexianxianxian committed
46 47 48 49 50 51 52 53 54 55
const mergeApi = (url, more) => {
  if (more && more.apiPrefix && typeof more.apiPrefix === 'string') {
    return `${config.apiPrefix}${url}`;
  }
  if (apiPrefix && typeof apiPrefix === 'string') {
    return `${config.apiPrefix}${url}`;
  }
  return url;
};

duanledexianxianxian's avatar
duanledexianxianxian committed
56 57 58 59
const headers = () => ({
  Authorization: store.get('token'),
});

duanledexianxianxian's avatar
duanledexianxianxian committed
60 61
const axios = new HttpRequest({
  baseUrl,
duanledexianxianxian's avatar
duanledexianxianxian committed
62
  headers: headers || {},
duanledexianxianxian's avatar
duanledexianxianxian committed
63 64 65 66 67 68 69
});

/**
 * 正常返回结果处理
 * @param {返回请求数据} response
 * @param {配置项} more
 */
duanledexianxianxian's avatar
duanledexianxianxian committed
70
const handleResponse = (response, more) => {
duanledexianxianxian's avatar
duanledexianxianxian committed
71 72 73 74 75
  const { data } = response;
  //
  if (`${data[resCodeKey]}` !== `${successCode}`) {
    if (isThrowError) {
      const errorMessage = data[resMessageKey] || '后端接口返回异常';
duanledexianxianxian's avatar
sync  
duanledexianxianxian committed
76 77
      let error = new Error();
      error = { ...error, ...data };
duanledexianxianxian's avatar
duanledexianxianxian committed
78
      error.code = data[resCodeKey];
duanledexianxianxian's avatar
duanledexianxianxian committed
79
      error.message = errorMessage;
duanledexianxianxian's avatar
duanledexianxianxian committed
80
      return Promise.reject(error);
duanledexianxianxian's avatar
duanledexianxianxian committed
81 82
    }
  }
duanledexianxianxian's avatar
sync  
duanledexianxianxian committed
83
  // success
duanledexianxianxian's avatar
duanledexianxianxian committed
84 85
  return data;
};
duanledexianxianxian's avatar
duanledexianxianxian committed
86

duanledexianxianxian's avatar
duanledexianxianxian committed
87 88
const handleError = error => {
  const { response } = error;
duanledexianxianxian's avatar
duanledexianxianxian committed
89
  // status
duanledexianxianxian's avatar
duanledexianxianxian committed
90
  if (response && response.status) {
duanledexianxianxian's avatar
sync  
duanledexianxianxian committed
91 92 93 94 95 96
    const errorText = codeMessage[response.status] || response.statusText;
    const {
      status,
      config: { url },
    } = response;
    notification.error({
duanledexianxianxian's avatar
duanledexianxianxian committed
97 98
      message: `请求错误 ${status}`,
      description: `${url}${errorText}`,
duanledexianxianxian's avatar
sync  
duanledexianxianxian committed
99
    });
duanledexianxianxian's avatar
duanledexianxianxian committed
100 101 102 103 104 105 106 107 108 109 110
    // if (status >= 404 && status < 422) {
    //   router.push('/exception/404');
    // }
    if (status <= 504 && status >= 500) {
      router.push('/exception/500');
    }
    // 跳转到登录页面 可能原因:token 失效
    if (status === 403 && status === 401) {
      clearLoginStatus();
      router.push('/user/login');
    }
duanledexianxianxian's avatar
sync  
duanledexianxianxian committed
111
  } else {
duanledexianxianxian's avatar
duanledexianxianxian committed
112
    // code
duanledexianxianxian's avatar
sync  
duanledexianxianxian committed
113
    const { code, message } = error;
duanledexianxianxian's avatar
duanledexianxianxian committed
114
    notification.error({
duanledexianxianxian's avatar
sync  
duanledexianxianxian committed
115 116 117
      key: `notification_${code ? message : code}`,
      message: '请求错误',
      description: message,
duanledexianxianxian's avatar
duanledexianxianxian committed
118
    });
duanledexianxianxian's avatar
duanledexianxianxian committed
119 120 121 122 123 124
    // 跳转到登录页面 可能原因:token 失效
    if (authCodes && authCodes.includes(code)) {
      // 清空相关信息
      clearLoginStatus();
      router.push('/user/login');
    }
duanledexianxianxian's avatar
duanledexianxianxian committed
125
  }
duanledexianxianxian's avatar
duanledexianxianxian committed
126

duanledexianxianxian's avatar
sync  
duanledexianxianxian committed
127 128 129 130 131
  if (isThrowError) {
    throw error;
  } else {
    return error;
  }
duanledexianxianxian's avatar
duanledexianxianxian committed
132 133
};

duanledexianxianxian's avatar
duanledexianxianxian committed
134 135 136 137 138 139
export default function request(url, options = {}, more = {}) {
  let newOptions = options;
  newOptions.url = url;
  if (more.headers) {
    newOptions = { ...options, headers: more.headers };
  }
duanledexianxianxian's avatar
duanledexianxianxian committed
140 141 142 143
  return axios
    .request(newOptions)
    .then(response => handleResponse(response, more))
    .catch(error => handleError(error));
duanledexianxianxian's avatar
duanledexianxianxian committed
144 145
}

duanledexianxianxian's avatar
duanledexianxianxian committed
146
const get = (url, data, more = {}) =>
duanledexianxianxian's avatar
duanledexianxianxian committed
147 148 149 150 151 152 153 154
  request(
    `${mergeApi(url, more)}`,
    {
      method: 'get', // default
      params: data,
    },
    more,
  );
duanledexianxianxian's avatar
duanledexianxianxian committed
155 156

const post = (url, data, more = {}) =>
duanledexianxianxian's avatar
duanledexianxianxian committed
157 158 159 160 161 162 163 164
  request(
    `${mergeApi(url, more)}`,
    {
      method: 'post', // default
      data,
    },
    more,
  );
duanledexianxianxian's avatar
duanledexianxianxian committed
165 166

const put = (url, data, more = {}) =>
duanledexianxianxian's avatar
duanledexianxianxian committed
167 168 169 170 171 172 173 174
  request(
    `${mergeApi(url, more)}`,
    {
      method: 'put', // default
      data,
    },
    more,
  );
duanledexianxianxian's avatar
duanledexianxianxian committed
175 176

const del = (url, data, more = {}) =>
duanledexianxianxian's avatar
duanledexianxianxian committed
177 178 179 180 181 182 183 184
  request(
    `${mergeApi(url, more)}`,
    {
      method: 'delete', // default
      data,
    },
    more,
  );
duanledexianxianxian's avatar
duanledexianxianxian committed
185 186

const patch = (url, data, more = {}) =>
duanledexianxianxian's avatar
duanledexianxianxian committed
187 188 189 190 191 192 193 194 195
  request(
    `${mergeApi(url, more)}`,
    {
      method: 'patch', // default
      data,
      ...more,
    },
    more,
  );
duanledexianxianxian's avatar
duanledexianxianxian committed
196 197 198 199 200 201 202 203

const formDataUpload = (url, data, more = {}) => {
  const formData = new FormData();
  if (data) {
    Object.keys(data).forEach(key => {
      formData.append(key, data[key]);
    });
  }
duanledexianxianxian's avatar
duanledexianxianxian committed
204
  post(`${mergeApi(url, more)}`, formData, {
duanledexianxianxian's avatar
duanledexianxianxian committed
205 206 207 208 209 210 211
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    ...more,
  });
};

duanledexianxianxian's avatar
duanledexianxianxian committed
212 213 214 215 216 217 218
/**
 * 上传文件
 * @param {url} url
 * @param {data} data
 * @param {type} type
 * @param {more} more
 */
duanledexianxianxian's avatar
duanledexianxianxian committed
219 220 221 222 223 224
const uploadFile = (url, data, type = 'formData', more = {}) => {
  if (type === 'formData') {
    formDataUpload(url, data, more);
  }
};

duanledexianxianxian's avatar
duanledexianxianxian committed
225
export { request, get, post, put, del, patch, uploadFile };