request.js 1.47 KB
import { Modal } from "antd";
import fetch from "dva/fetch";

function parseJSON(response) {
  return response.json();
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  } else {
    Modal.confirm({
      title: "温馨提示:",
      content: (
        <div>
          <div>
            接口【
            {response.url.split("?")[0]}
            】请求失败!
          </div>
          <div>是否跳转到登录页面?</div>
        </div>
      ),
      okText: "确认",
      cancelText: "取消",
      onOk() {
        window.location.href = location.origin;
      },
      onCancel() {
        window.instructSetLock = false;
      }
    });
    return response;
  }

  // const error = new Error(response.statusText);
  // error.response = response;
  // throw error;
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options) {
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => {
      if (
        (data.status >= 200 && data.status < 300) ||
        data.code !== undefined
      ) {
        return { data };
      } else {
        return { data: { ...data, msg: "请求失败!" } };
      }
    })
    .catch(err => ({ err }));
}