request.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // +----------------------------------------------------------------------
  2. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  3. // +----------------------------------------------------------------------
  4. // | Copyright (c) 2016~2021 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. checkLogin
  17. } from '../libs/login';
  18. import store from '../store';
  19. function toLogin(){
  20. store.commit("LOGOUT");
  21. uni.showToast({
  22. title: '请登录',
  23. icon: 'none',
  24. duration: 1000
  25. });
  26. }
  27. /**
  28. * 发送请求
  29. */
  30. function baseRequest(url, method, data, {
  31. noAuth = false,
  32. noVerify = false
  33. }) {
  34. let Url = HTTP_REQUEST_URL,
  35. header = HEADER;
  36. if (!noAuth) {
  37. //登录过期自动登录
  38. if (!store.state.app.token && !checkLogin()) {
  39. toLogin();
  40. return Promise.reject({
  41. msg: '未登录'
  42. });
  43. }
  44. }
  45. if (store.state.app.token) header[TOKENNAME] = 'Bearer ' + store.state.app.token;
  46. return new Promise((reslove, reject) => {
  47. uni.request({
  48. url: Url + '/api/' + url,
  49. method: method || 'GET',
  50. header: header,
  51. data: data || {},
  52. success: (res) => {
  53. // #ifdef APP-PLUS
  54. console.log('app', Url + '/api/' + url, res.data);
  55. // #endif
  56. if (noVerify)
  57. reslove(res.data, res);
  58. else if (res.data.status == 200)
  59. reslove(res.data, res);
  60. else if ([410000, 410001, 410002, 40000].indexOf(res.data.status) !== -1) {
  61. toLogin();
  62. reject(res.data);
  63. } else if (res.data.status == 501) {
  64. uni.reLaunch({
  65. url: '/pages/error/index'
  66. })
  67. reject(res.data);
  68. } else
  69. reject(res.data.message || '系统错误');
  70. },
  71. fail: (message) => {
  72. reject('请求失败');
  73. }
  74. })
  75. });
  76. }
  77. const request = {};
  78. ['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
  79. request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
  80. });
  81. export default request;