request.js 8.7 KB
Newer Older
1 2 3 4
import fetch from 'dva/fetch';
import router from 'umi/router';
import moment from 'moment';
import FormdataWrapper from '@/webPublic/zyd_public/utils/object-to-formdata-custom';
5 6 7 8 9 10
import {
  isJSON,
  controlNotification,
  getIsBei_Dian,
  getHeaders,
} from '@/webPublic/zyd_public/utils/utils';
11 12 13
import config from '@/config/config';
import apiConfig from './apiSystemConfig';
import { omit } from 'lodash';
14
import qs from 'qs';
15 16
import { queryIsSafe } from '@/webPublic/one_stop_public/utils/queryConfig';
import { uaaRequest } from '@/webPublic/one_stop_public/utils/request';
17 18 19 20 21
import {
  getToken,
  setFetchUrl,
  getFetchUrl,
  getType,
22
  delToken
23
} from '@/webPublic/one_stop_public/utils/token';
24
import urlTransform from '@/webPublic/zyd_public/request/urlTransform';
25
import { proxyChangeUrl } from '@/webPublic/zyd_public/request/proxyChangeUrl';
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

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队(异步任务)。',
  204: '删除数据成功。',
  400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
  401: '登录已过期,请重新登录',
  403: '用户得到授权,但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除,且不会再得到的。',
  422: '当创建一个对象时,发生一个验证错误。',
  500: '服务器发生错误,请检查服务器。',
  502: '网关错误。',
  503: '服务不可用,服务器暂时过载或维护。',
  504: '网关超时。',
};

const checkStatus = response => {
  if (response.status !== 401) {
    return response;
  }
  const errortext = codeMessage[response.status] || response.statusText;
  const token = getToken();
  if (token && token !== 'null') {
    controlNotification({
      message: `${response.status === 401 ? '登录过期' : '请求错误'}`,
      description: errortext,
    });
  }
  if (response.status === 401) {
59
     delToken();
60 61
    if (window.top != window.self) {
      window.top.postMessage('returnLogin', '*'); // Iframe 返回登录页
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 94 95 96 97
      return true;
    }
  }
  const error = new Error(errortext);
  error.name = response.status;
  error.response = response;
  throw error;
};

const cachedSave = (response, hashcode) => {
  /**
   * Clone a response data and store it in sessionStorage
   * Does not support data other than json, Cache only json
   */
  const contentType = response.headers.get('Content-Type');
  if (contentType && contentType.match(/application\/json/i)) {
    // All data is saved as text
    response
      .clone()
      .text()
      .then(content => {
        sessionStorage.setItem(hashcode, content);
        sessionStorage.setItem(`${hashcode}:timestamp`, Date.now());
      });
  }
  return response;
};

async function queryDemo() {
  return false;
}

function setFetchInfo(url, options) {
  let session = getFetchUrl();
  if (isJSON(session)) {
    session = JSON.parse(session);
98 99
    if (session.url === url && moment()
      .valueOf() - session.time < 500) {
100
      if (options.body && JSON.stringify(options.body) === session.body) {
101
        console.log('频繁调用接口: ', url, options.body);
102 103 104 105 106 107 108
        return false;
      }
    }
  }

  return JSON.stringify({
    url,
109 110
    time: moment()
      .valueOf(),
111 112 113 114 115 116 117 118 119 120 121
    body: options.body ? JSON.stringify(options.body) : '',
  });
}

/**
 * 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"
 */
122

123 124 125 126
export default function request(
  url,
  options = {},
) {
127
  url = urlTransform(url); // 北电科接口越权修改
128 129 130 131
  if (url && url.indexOf('/CmsApi/') > -1 && queryIsSafe() && url.indexOf('/CmsApi/getExportInfo') <= -1) {
    url = url.replace(config.httpServer, '');
    return uaaRequest(url, options.body);
  }
132
  url = proxyChangeUrl(url);
133 134 135 136 137 138 139 140 141

  let sessionFetch = setFetchInfo(url, options);
  if (!sessionFetch) {
    return queryDemo();
  } else {
    setFetchUrl(sessionFetch);
  }
  let defaultToken = getToken();
  const token = defaultToken !== null && defaultToken !== 'null' ? defaultToken : '';
142 143
  if (url.indexOf('oauthPub=true') <= -1 && url.indexOf('uia/logout') <= -1 && !getIsBei_Dian()) {
    if (url.indexOf('?') > -1) {
钟是志's avatar
钟是志 committed
144
      url = url + '&token=' + token;
145
    } else {
钟是志's avatar
钟是志 committed
146
      url = url + '?token=' +  token;
钟是志's avatar
钟是志 committed
147
    }
148 149 150 151 152 153 154 155 156 157 158 159
  }

  if (options.time) {
    const time = new Date().getTime();
    if (url.indexOf('?') === -1) {
      url = url + '?time=' + time;
    } else {
      url = url + '&time=' + time;
    }
  }

  const defaultOptions = {
钟是志's avatar
钟是志 committed
160 161
    credentials: 'omit', // 确保浏览器不在请求中包含凭据 // 用这个本地访问北电科会跨域
    // credentials: 'include', // 为了让浏览器发送包含凭据的请求(即使是跨域源)   // 用这个 本地访问黔南会跨域
162 163 164 165 166 167 168 169 170 171
    mode: 'cors',
  };
  let newOptions = { ...defaultOptions, ...options };
  if (newOptions.method === 'POST' ||
    newOptions.method === 'PUT' ||
    newOptions.method === 'DELETE') {
    if (!(newOptions.body instanceof FormData)) {
      newOptions.headers = {
        Accept: 'application/json',
        ...newOptions.headers,
172
        ...getHeaders(url).headers,
173 174 175 176 177 178 179 180
      };
      newOptions.body = FormdataWrapper(newOptions.body);
    } else {
      // newOptions.body is FormData
      newOptions.headers = {
        Accept: 'application/json',
        'Content-Type': 'multipart/form-data',
        ...newOptions.headers,
181
        ...getHeaders(url).headers,
182 183 184 185
      };
    }
  }
  if (newOptions.method === 'GET') {
186
    let splitCode = '&';
187
    if(url && url.indexOf('?') <= -1){
188
      splitCode = '?';
189
    }
190
    url = url + splitCode + qs.stringify(newOptions.body || {});
191
    newOptions = omit(newOptions, 'body');
钟是志's avatar
钟是志 committed
192 193 194
    newOptions.headers = {
      ...getHeaders().headers,
    };
195 196
  }

197
  if (!token || token === 'null' || url.indexOf('uia/logout') > -1) {
198 199 200 201 202 203 204 205 206 207 208 209 210
    delete newOptions.headers.Authorization;
  }

  return fetch(url, newOptions)
    .then(checkStatus)
    //.then(response => cachedSave(response, hashcode))
    .then(response => {
      if (response.status !== 200) {
        return response.text();
      }
      return response.json();
    })
    .then(response => {
钟是志's avatar
钟是志 committed
211
      if (typeof response === 'string') {
212 213
        try {
          const xxx = JSON.parse(response);
214
          if (xxx.status === 404) {
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
            controlNotification({
              message: '接口异常',
            });
            return null;
          }
          if (xxx.errMsg || xxx.message) {
            controlNotification({
              //message: '',
              message: xxx.errMsg || xxx.message,
            });
            return null;
          }
          return xxx;
        } catch (e) {
          return response;
        }
      }
      return response;
    })
    .catch(e => {

      const status = e.name;
钟是志's avatar
钟是志 committed
237 238
      if (status === 401) { // 401直接清空token
         delToken();
钟是志's avatar
钟是志 committed
239

240 241
        if (window.top != window.self) {
          window.top.postMessage('returnLogin', '*'); // Iframe 返回登录页
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
          return true;
        }
        // @HACK
        /* eslint-disable no-underscore-dangle */
        window.g_app._store.dispatch({
          type: 'login/logout',
        });
        return false;
      }
      // environment should not be used
      if (status === 403) {
        router.push('/exception/403');
        return false;
      }
      if (status <= 504 && status >= 500) {
        router.push('/exception/500');
        return false;
      }
      if (status >= 404 && status < 422) {
        router.push('/exception/404');
      }


      let systemName = '学工系统';
      let type = getType();
      if (url.indexOf('/v1/api/zydxgWeb/') > -1 && type) {
        let reg = new RegExp('/', 'g');
        type = type && type.replace(reg, '');
        systemName = config.systems[type] && config.systems[type].name || systemName;
      } else {
        let findApiConfig = apiConfig.find((x) => {
          return url.indexOf(x.path) > -1;
        });
        systemName = findApiConfig && findApiConfig.name || '系统';
      }

278 279
      if (!window.navigator.onLine) {
        return controlNotification({
280 281 282 283 284 285 286 287
          message: '网络故障',
          description: `${systemName}无法连接到网络,请稍后再试`,
        });
      }
      controlNotification({
        message: '网络故障',
        description: `${systemName}无法连接到服务器,请稍后再试`,
      });
288 289
      if (window.top != window.self) {
        window.top.postMessage('returnLogin', '*'); // Iframe 返回登录页
290 291 292 293 294
        return true;
      }
      return;
    });
}