request.js 1.8 KB

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