Connection.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * 在 ajax request 前修改url,增加服务端`basePath`
  3. * `basePath`在`app.json`配置
  4. */
  5. Ext.define('saas.override.data.Connection', {
  6. override: 'Ext.data.Connection',
  7. urlRegexp: /(http|ftp|https):\/\//,
  8. config: {
  9. /**
  10. * @cfg {Object} defaultServerHeaders
  11. * 与defaultHeaders有区别,只在调用server api的时候才添加的headers
  12. */
  13. defaultServerHeaders: null
  14. },
  15. privates: {
  16. parseBasePath: function(basePath) {
  17. if (Ext.isObject(basePath)) {
  18. var protocol = window.location.protocol.split(":")[0];
  19. if (protocol === 'file') {
  20. protocol = 'https';
  21. }
  22. return basePath[protocol];
  23. }
  24. return basePath;
  25. },
  26. setupServerOptions: function(options) {
  27. var serverOptions = Ext.manifest.server, originUrl = options.url;
  28. if (serverOptions && serverOptions.basePath && !this.urlRegexp.test(originUrl) &&
  29. (!serverOptions.urlPattern || new RegExp(serverOptions.urlPattern).test(originUrl))) {
  30. Ext.Object.merge(options, {
  31. url: this.parseBasePath(serverOptions.basePath)
  32. + (originUrl.indexOf('/') == 0 ? '' : '/') + originUrl,
  33. headers: this.getDefaultServerHeaders() || {}
  34. });
  35. }
  36. }
  37. },
  38. request: function(options) {
  39. if (options && options.url) {
  40. this.setupServerOptions(options);
  41. }
  42. return this.callParent([options]);
  43. },
  44. onRequestComplete: function(request) {
  45. let headers = request.result.getAllResponseHeaders() || {},
  46. Authorization = headers['authorization'],
  47. result = request.result,
  48. res;
  49. try{
  50. res = JSON.parse(result.responseText);
  51. }catch(e) {
  52. res = result.responseJson
  53. // console.error(e);
  54. }
  55. if(res && res.code == 40001) {
  56. // 如果token超时则显示重新登陆弹窗
  57. saas.util.BaseUtil.showLoginWin();
  58. throw new Error('会话已过期');
  59. }
  60. if(Authorization) {
  61. // 如果返回了token则刷新token
  62. let headers = Ext.Ajax.getDefaultHeaders() || {};
  63. let session = saas.util.State.get('session');
  64. headers['Authorization'] = Authorization;
  65. Ext.Ajax.setDefaultHeaders(headers);
  66. session.token = Authorization;
  67. session.timestamp = Ext.now();
  68. saas.util.State.set('session', session);
  69. let sessionStr = JSON.stringify(session.data);
  70. const frame = window.frames[window.frames.length - 1];
  71. frame.postMessage(sessionStr, '*');
  72. }
  73. },
  74. });