request.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. import fetch from 'dva/fetch';
  2. import { loginOut, setLocalStorageTime, getLocalStorageStingVal } from './utils';
  3. import { language_type } from './util_data';
  4. import { parse } from 'qs';
  5. import { getLocale } from 'umi/locale';
  6. import React from 'react';
  7. const codeMessage = {
  8. 200: '服务器成功返回请求的数据。',
  9. 201: '新建或修改数据成功。',
  10. 202: '一个请求已经进入后台排队(异步任务)。',
  11. 204: '删除数据成功。',
  12. 400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
  13. 401: '用户没有权限(令牌、用户名、密码错误)。',
  14. 403: '用户得到授权,但是访问是被禁止的。',
  15. 404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
  16. 406: '请求的格式不可得。',
  17. 410: '请求的资源被永久删除,且不会再得到的。',
  18. 422: '当创建一个对象时,发生一个验证错误。',
  19. 500: '服务器发生错误,请检查服务器。',
  20. 502: '网关错误。',
  21. 503: '服务不可用,服务器暂时过载或维护。',
  22. 504: '网关超时。',
  23. 245: '抱歉,您没有操作该功能的权限!',
  24. };
  25. const checkStatus = response => {
  26. if (response.status >= 200 && response.status < 300) {
  27. return response;
  28. }
  29. const errortext = codeMessage[response.status] || response.statusText;
  30. const error = new Error(errortext);
  31. error.name = response.status;
  32. error.response = response;
  33. throw error;
  34. };
  35. const cachedSave = (response, hashcode) => {
  36. /**
  37. * Clone a response data and store it in sessionStorage
  38. * Does not support data other than json, Cache only json
  39. */
  40. const contentType = response.headers.get('Content-Type');
  41. if (contentType && contentType.match(/application\/json/i)) {
  42. // All data is saved as text
  43. response
  44. .clone()
  45. .text()
  46. .then(content => {
  47. sessionStorage.setItem(hashcode, content);
  48. sessionStorage.setItem(`${hashcode}:timestamp`, Date.now());
  49. });
  50. }
  51. return response;
  52. };
  53. /**
  54. * Requests a URL, returning a promise.
  55. *
  56. * @param {string} url The URL we want to request
  57. * @param {object} [option] The options we want to pass to "fetch"
  58. * @return {object} An object containing either "data" or "err"
  59. */
  60. export default function request(url, options, type = '') {
  61. const defaultOptions = {
  62. credentials: 'include',
  63. };
  64. let newOptions = { ...defaultOptions, ...options };
  65. if (newOptions.headers == undefined) {
  66. newOptions.headers = {};
  67. }
  68. //设置当前语言
  69. const selectedLang = getLocale();
  70. let api_language = language_type().filter(item=>item.key == selectedLang)[0].val;
  71. newOptions.headers.Language = api_language;
  72. //请求接口需要有登录认证请求头,只有登录接口需要传递授权认证,其余接口为token
  73. if (url.indexOf('adminLogin/oauth/token') > -1) {
  74. newOptions.headers.Authorization = 'Basic VVcxS2FsRlhVblJoVnpROTpVMjFHTWxsVlFrUmlNMEkxVlcxc2JtRklVa0ZWTW5oMldrYzVkUT09';
  75. } else {
  76. newOptions.headers.Authorization = 'Bearer ' + getLocalStorageStingVal('sld_token');
  77. }
  78. if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
  79. if (!(newOptions.body instanceof FormData)) {
  80. newOptions.headers = {
  81. Accept: 'application/json',
  82. 'Content-Type': type == 'json' ? 'application/json' : 'application/x-www-form-urlencoded',
  83. ...newOptions.headers,
  84. };
  85. if (type == 'json') {
  86. newOptions.body = JSON.stringify(newOptions.body);
  87. }
  88. } else {
  89. // newOptions.body is FormData
  90. newOptions.headers = {
  91. Accept: 'application/json',
  92. 'Content-Type': 'multipart/form-data',
  93. ...newOptions.headers,
  94. };
  95. }
  96. }
  97. let fileName = '';//导出的文件名
  98. return fetch(url, newOptions)
  99. .then(checkStatus)
  100. .then((response) => {
  101. if (response.headers.get('Content-Type').indexOf('json') == -1) {//导出功能
  102. let params = parse(url.split('?')[1]);
  103. fileName = params.fileName;
  104. if (response.headers.get('Content-Type').indexOf('excel') > -1) {//导出excel
  105. fileName += '.xls';
  106. }else {//导出zip
  107. fileName += '.zip';
  108. }
  109. return response.blob();
  110. }
  111. if (newOptions.method === 'DELETE' || response.status === 204) {
  112. return response.text();
  113. }
  114. return response.json();
  115. }).then(data => {
  116. if (data.state == undefined) {
  117. download(data, fileName);//下载文件
  118. return false;
  119. }
  120. if (data.state != undefined && (data.state == 501 || data.state === 266)) {
  121. loginOut();
  122. } else {
  123. // 更新sld_token的时间
  124. // {
  125. // setLocalStorageTime();
  126. // }
  127. return data;
  128. }
  129. }).catch((e) => {
  130. return { state: 500, msg: '请刷新页面~' };
  131. });
  132. }
  133. function download(blobData, forDownLoadFileName = '') {
  134. const aLink = document.createElement('a');
  135. document.body.appendChild(aLink);
  136. aLink.style.display = 'none';
  137. aLink.href = window.URL.createObjectURL(blobData);
  138. aLink.setAttribute('download', forDownLoadFileName);
  139. aLink.click();
  140. document.body.removeChild(aLink);
  141. }