request.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // +----------------------------------------------------------------------
  2. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  3. // +----------------------------------------------------------------------
  4. // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  5. // +----------------------------------------------------------------------
  6. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  7. // +----------------------------------------------------------------------
  8. // | Author: CRMEB Team <admin@crmeb.com>
  9. // +----------------------------------------------------------------------
  10. import {
  11. HTTP_REQUEST_URL,
  12. HEADER,
  13. TOKENNAME
  14. } from '@/config/app';
  15. import {
  16. toLogin,
  17. checkLogin
  18. } from '../libs/login';
  19. import store from '../store';
  20. import i18n from './lang.js';
  21. /**
  22. * 发送请求
  23. */
  24. function baseRequest(url, method, data, {
  25. noAuth = false,
  26. noVerify = false
  27. }) {
  28. let Url = HTTP_REQUEST_URL,
  29. header = HEADER;
  30. if (!noAuth) {
  31. //登录过期自动登录
  32. if (!store.state.app.token && !checkLogin()) {
  33. toLogin();
  34. return Promise.reject({
  35. msg: i18n.t(`未登录`)
  36. });
  37. }
  38. }
  39. if (store.state.app.token) header[TOKENNAME] = 'Bearer ' + store.state.app.token;
  40. return new Promise((reslove, reject) => {
  41. if (uni.getStorageSync('locale')) {
  42. header['Cb-lang'] = uni.getStorageSync('locale')
  43. }
  44. uni.request({
  45. url: Url + '/api/' + url,
  46. method: method || 'GET',
  47. header: header,
  48. data: data || {},
  49. success: (res) => {
  50. if (noVerify)
  51. reslove(res.data, res);
  52. else if (res.data.status == 200)
  53. reslove(res.data, res);
  54. else if ([110002, 110003, 110004].indexOf(res.data.status) !== -1) {
  55. toLogin();
  56. reject(res.data);
  57. } else if (res.data.status == 100103) {
  58. uni.showModal({
  59. title: i18n.t(`提示`),
  60. content: res.data.msg,
  61. showCancel: false,
  62. confirmText: i18n.t(`我知道了`)
  63. });
  64. } else
  65. reject(res.data.msg || i18n.t(`系统错误`));
  66. },
  67. fail: (msg) => {
  68. let data = {
  69. mag: i18n.t(`请求失败`),
  70. status: 1 //1没网
  71. }
  72. // #ifdef APP-PLUS
  73. reject(data);
  74. // #endif
  75. // #ifndef APP-PLUS
  76. reject(i18n.t(`请求失败`));
  77. // #endif
  78. }
  79. })
  80. });
  81. }
  82. const request = {};
  83. ['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
  84. request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
  85. });
  86. export default request;