request.js 2.51 KB
Newer Older
wuhao's avatar
wuhao committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
/* eslint-disable eqeqeq */
/**
 * request 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request
 */
import { history } from "umi";
import { message } from "antd";
import { extend } from "umi-request";

const errorHandler = (error) => {
  const { response } = error;
  // if (response && response.status) {
  //   const errorText = codeMessage[response.status] || response.statusText;
  //   const { status, url } = response;
  //   if (response?.url.indexOf('api/user_token') == -1) {
  //     notification.error({
  //       message: `请求错误 ${status}: ${url}`,
  //       description: errorText,
  //     });
  //   }
  // } else if (!response) {
  //   if (response?.url.indexOf('api/user_token') == -1) {
  //     notification.error({
  //       description: '您的网络发生异常,无法连接服务器',
  //       message: '网络异常',
  //     });
  //   }
  // }

  return response ? response : {};
};
/**
 * 配置request请求时的默认参数
 */

const request = extend({
  prefix: REACT_APP_URL, //前缀代理  tasks.nangaoyun.com
  errorHandler,
  // 默认错误处理
  credentials: "include", // 默认请求是否带上cookie
});

// request拦截器, 改变url 或 options.
request.interceptors.request.use(async (url, options) => {
  let token = localStorage.getItem("TOKENSTRING");
  if (token) {
    const headers =
      options.type == "form"
        ? {
            Authorization: token,
          }
        : {
            "Content-Type": "application/json",
            Authorization: token,
          };
    return {
      url: url,
      options: { ...options, headers: headers },
    };
  }
});

// response拦截器, 处理response
request.interceptors.response.use(async (response, options) => {
  if (options.url === "/webtool/v1/storeexport"|| options.url === "/webtool/v1/purchaseexport") {
    const data = await response.clone().blob();
    let blobUrl = window.URL.createObjectURL(data);
    const a = document.createElement("a");
    a.style.display = "none";
    let pathname = options.params.filename;
    a.download = pathname + ".xls";
    a.href = blobUrl;
    a.click();
    a.remove();
    return;
  }
  const data = await response.clone().json();

  // 详情返回的response处理
  if (data?.code !== 0) {
    if (data?.error || data?.code === -1) {
      console.log(location.origin);
      localStorage.removeItem("TOKENSTRING");
      history.replace("/user/login");
    } else {
      message.error(data?.msg);
    }
  }

  return response;
});

export default request;