app.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { history, useModel } from "@umijs/max";
  2. // 运行时配置
  3. // 全局初始化数据配置,用于 Layout 用户信息和权限初始化
  4. // 更多信息见文档:https://umijs.org/docs/api/runtime-config#getinitialstate
  5. export async function getInitialState(): Promise<{ name: string }> {
  6. return { name: '@umijs/max' };
  7. }
  8. /**
  9. * 配置请求
  10. */
  11. export const request = {
  12. requestInterceptors: [
  13. (url: string, options: any) => {
  14. options.headers = {
  15. ...options.headers,
  16. Authorization: `${localStorage.getItem('token') ? 'Bearer ' + localStorage.getItem('token') : ''}`,
  17. };
  18. return { url, options };
  19. },
  20. ],
  21. errorConfig: {
  22. errorHandler: (error: any) => {
  23. if (error.response.status === 401) {
  24. localStorage.removeItem("token");
  25. history.push('/login');
  26. }
  27. },
  28. },
  29. };
  30. // 配置路由跳转
  31. export function onRouteChange({ location }: any) {
  32. const token = localStorage.getItem('token');
  33. // 正确用法:解构 state 和 actions
  34. // 未登录且不在登录页,跳转到登录页
  35. if (!token && (location.pathname !== '/login' && location.pathname !== '/login/callback' )) {
  36. history.push('/login?redirect=' + encodeURIComponent(location.pathname));
  37. }
  38. if(location.pathname !== '/play') {
  39. }
  40. // 已登录却访问登录页,跳转到首页
  41. if (token && location.pathname === '/login') {
  42. history.push('/');
  43. }
  44. }