app.jsx 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. import { PageLoading } from '@ant-design/pro-layout';
  2. import { notification,Modal,message } from 'antd';
  3. import { history, Link ,useModel} from 'umi';
  4. import RightContent from '@/components/RightContent';
  5. import Footer from '@/components/Footer';
  6. import { currentUser as queryCurrentUser,outLogin } from './services/ant-design-pro/api';
  7. import { BookOutlined, LinkOutlined } from '@ant-design/icons';
  8. import {getQueryString} from './utils';
  9. import { stringify } from 'querystring';
  10. import {getSubHosp} from './services/user';
  11. const defaultMenus = [
  12. {
  13. path: '/',
  14. name: 'welcome',
  15. icon: 'smile',
  16. children: [
  17. {
  18. path: '/welcome',
  19. name: 'one',
  20. icon: 'smile',
  21. children: [
  22. {
  23. path: '/welcome/welcome',
  24. name: 'two',
  25. icon: 'smile',
  26. exact: true,
  27. },
  28. ],
  29. },
  30. ],
  31. },
  32. {
  33. path: '/responsibilityCenter',
  34. name: 'demo',
  35. icon: 'heart',
  36. },
  37. ];
  38. const isDev = process.env.NODE_ENV === 'development';
  39. const loginPath = '/user/login';
  40. let requestMethod = 'get';
  41. /** 获取用户信息比较慢的时候会展示一个 loading */
  42. export const initialStateConfig = {
  43. loading: <PageLoading />,
  44. };
  45. /**
  46. * @see https://umijs.org/zh-CN/plugins/plugin-initial-state
  47. * */
  48. export async function getInitialState() {
  49. const fetchUserInfo = async () => {
  50. const userData = localStorage.getItem('userData');
  51. if(userData){
  52. return JSON.parse(userData);
  53. }
  54. return undefined;
  55. }; // 如果是登录页面,不执行
  56. //医院标识
  57. const sign = getQueryString('hospSign');
  58. const fetchSubHosp = async ()=>{
  59. // try {
  60. // const msg = await getSubHosp(sign);
  61. // } catch (error) {
  62. // }
  63. }
  64. if (history.location.pathname !== loginPath) {
  65. const currentUser = await fetchUserInfo();
  66. return {
  67. fetchUserInfo,
  68. currentUser,
  69. settings: {},
  70. isExpired:false,
  71. fetchSubHosp,
  72. sign
  73. };
  74. }
  75. return {
  76. fetchUserInfo,
  77. settings: {},
  78. fetchSubHosp,
  79. sign
  80. };
  81. }
  82. /**
  83. * 退出登录,并且将当前的 url 保存
  84. */
  85. const loginOut = async () => {
  86. // await outLogin();
  87. const { query = {}, pathname } = history.location;
  88. const { redirect,hospSign } = query; // Note: There may be security issues, please note
  89. const loginParams = localStorage.getItem('loginParams');
  90. let sign;
  91. if(loginParams){
  92. const {hospSign,hospId} = JSON.parse(loginParams);
  93. sign = hospSign;
  94. }
  95. // &hospSign=${sign}
  96. // console.log({redirect,hospSign})
  97. if (window.location.pathname !== `/user/login` && !redirect) {
  98. history.replace({
  99. pathname: `/user/login`,
  100. search: stringify({
  101. redirect: pathname,
  102. hospSign:sign
  103. }),
  104. });
  105. }
  106. };
  107. /**
  108. * 异常处理程序
  109. 200: '服务器成功返回请求的数据。',
  110. 201: '新建或修改数据成功。',
  111. 202: '一个请求已经进入后台排队(异步任务)。',
  112. 204: '删除数据成功。',
  113. 400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
  114. 401: '用户没有权限(令牌、用户名、密码错误)。',
  115. 403: '用户得到授权,但是访问是被禁止的。',
  116. 404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
  117. 405: '请求方法不被允许。',
  118. 406: '请求的格式不可得。',
  119. 410: '请求的资源被永久删除,且不会再得到的。',
  120. 422: '当创建一个对象时,发生一个验证错误。',
  121. 500: '服务器发生错误,请检查服务器。',
  122. 502: '网关错误。',
  123. 503: '服务不可用,服务器暂时过载或维护。',
  124. 504: '网关超时。',
  125. //-----English
  126. 200: The server successfully returned the requested data. ',
  127. 201: New or modified data is successful. ',
  128. 202: A request has entered the background queue (asynchronous task). ',
  129. 204: Data deleted successfully. ',
  130. 400: 'There was an error in the request sent, and the server did not create or modify data. ',
  131. 401: The user does not have permission (token, username, password error). ',
  132. 403: The user is authorized, but access is forbidden. ',
  133. 404: The request sent was for a record that did not exist. ',
  134. 405: The request method is not allowed. ',
  135. 406: The requested format is not available. ',
  136. 410':
  137. 'The requested resource is permanently deleted and will no longer be available. ',
  138. 422: When creating an object, a validation error occurred. ',
  139. 500: An error occurred on the server, please check the server. ',
  140. 502: Gateway error. ',
  141. 503: The service is unavailable. ',
  142. 504: The gateway timed out. ',
  143. * @see cd
  144. */
  145. //请求拦截器
  146. const authHeaderInterceptor = (url, options) => {
  147. console.log({options});
  148. const {method} = options;
  149. if(method == 'post'){
  150. requestMethod='post'
  151. }else{
  152. requestMethod='get'
  153. }
  154. const userData = localStorage.getItem('userData');
  155. let authHeader = {};
  156. if(userData){
  157. const {token} = JSON.parse(userData);
  158. authHeader.token = token;
  159. }
  160. return {
  161. url: `${url}`,
  162. options: { ...options, interceptors: true, headers: authHeader },
  163. };
  164. };
  165. //响应拦截器
  166. const demoResponseInterceptors = async (response, options) => {
  167. // response.headers.append('interceptors', 'yes yo');
  168. // console.log({response});
  169. const {status} = response;
  170. if(status != 200){
  171. if(status == 500){
  172. notification.error({
  173. message: '抱歉,服务器出现错误!'
  174. });
  175. }
  176. if(status == 404){
  177. notification.error({
  178. message: '抱歉,服务器未找到请求!'
  179. });
  180. }
  181. return {};
  182. }
  183. const _response = await response.clone().json();
  184. const {status:dataStatus,msg,errorMessage,errorCode} = _response;
  185. //success返回
  186. if(dataStatus == 200){
  187. if(requestMethod=='post'&&history.location.pathname != loginPath){
  188. message.success('操作成功!');
  189. }
  190. return response;
  191. }else{
  192. if(errorCode==499){
  193. // setInitialState((s) => ({ ...s, isExpired:true}));
  194. Modal.confirm({
  195. title:'抱歉,登录已过期请重新登录!',
  196. onOk:()=>{
  197. loginOut();
  198. }
  199. });
  200. }else{
  201. notification.error({
  202. message:errorMessage,
  203. duration: 5,
  204. });
  205. }
  206. return {}
  207. }
  208. }
  209. export const request = {
  210. errorHandler: (error) => {
  211. console.log({error});
  212. const { response } = error;
  213. if (!response) {
  214. notification.error({
  215. description: '您的网络发生异常,无法连接服务器',
  216. message: '网络异常',
  217. });
  218. }
  219. throw error;
  220. },
  221. // 新增自动添加AccessToken的请求前拦截器
  222. requestInterceptors: [authHeaderInterceptor],
  223. responseInterceptors: [demoResponseInterceptors],
  224. }; // ProLayout 支持的api https://procomponents.ant.design/components/layout
  225. export const layout = ({ initialState }) => {
  226. return {
  227. rightContentRender: () => <RightContent />,
  228. disableContentMargin: false,
  229. waterMarkProps: {
  230. content:'',
  231. },
  232. footerRender: () => <Footer />,
  233. onPageChange: () => {
  234. const { location } = history; // 如果没有登录,重定向到 login
  235. if (!initialState?.currentUser && location.pathname !== loginPath) {
  236. history.push(loginPath);
  237. }
  238. },
  239. // menu: {
  240. // // 每当 initialState?.currentUser?.userid 发生修改时重新执行 request
  241. // // params: {
  242. // // userId: initialState?.currentUser?.userid,
  243. // // },
  244. // request: async (params, defaultMenuData) => {
  245. // // initialState.currentUser 中包含了所有用户信息
  246. // // const menuData = await fetchMenuData();
  247. // // return menuData;
  248. // return defaultMenus;
  249. // },
  250. // },
  251. links: isDev
  252. ? [
  253. <Link to="/umi/plugin/openapi" target="_blank">
  254. <LinkOutlined />
  255. <span>OpenAPI 文档</span>
  256. </Link>,
  257. <Link to="/~docs">
  258. <BookOutlined />
  259. <span>业务组件文档</span>
  260. </Link>,
  261. ]
  262. : [],
  263. menuHeaderRender: undefined,
  264. // 自定义 403 页面
  265. // unAccessible: <div>unAccessible</div>,
  266. ...initialState?.settings,
  267. };
  268. };