request.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. TIMEOUT
  15. } from '@/config/app';
  16. import {
  17. toLogin,
  18. checkLogin
  19. } from '../libs/login';
  20. import store from '../store';
  21. import i18n from './lang.js';
  22. /**
  23. * 发送请求
  24. */
  25. function baseRequest(url, method, data, {
  26. noAuth = false,
  27. noVerify = false
  28. }) {
  29. let Url = HTTP_REQUEST_URL,
  30. header = HEADER;
  31. if (!noAuth) {
  32. //登录过期自动登录
  33. if (!store.state.app.token && !checkLogin()) {
  34. toLogin();
  35. return Promise.reject({
  36. msg: i18n.t(`未登录`)
  37. });
  38. }
  39. }
  40. if (store.state.app.token) header[TOKENNAME] = 'Bearer ' + store.state.app.token;
  41. return new Promise((reslove, reject) => {
  42. if (uni.getStorageSync('locale')) {
  43. header['Cb-lang'] = uni.getStorageSync('locale')
  44. }
  45. uni.request({
  46. url: Url + '/api/' + url,
  47. method: method || 'GET',
  48. header: header,
  49. data: data || {},
  50. timeout: TIMEOUT,
  51. success: (res) => {
  52. if (noVerify)
  53. reslove(res.data, res);
  54. else if (res.data.status == 200)
  55. reslove(res.data, res);
  56. else if ([110002, 110003, 110004].indexOf(res.data.status) !== -1) {
  57. toLogin();
  58. reject(res.data);
  59. } else if (res.data.status == 100103) {
  60. uni.showModal({
  61. title: i18n.t(`提示`),
  62. content: res.data.msg,
  63. showCancel: false,
  64. confirmText: i18n.t(`我知道了`)
  65. });
  66. } else
  67. reject(res.data.msg || i18n.t(`系统错误`));
  68. },
  69. fail: (msg) => {
  70. let data = {
  71. mag: i18n.t(`请求失败`),
  72. status: 1 //1没网
  73. }
  74. // #ifdef APP-PLUS
  75. reject(data);
  76. // #endif
  77. // #ifndef APP-PLUS
  78. reject(i18n.t(`请求失败`));
  79. // #endif
  80. }
  81. })
  82. });
  83. }
  84. const request = {};
  85. ['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
  86. request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
  87. });
  88. export default request;