request.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. console.log(res);
  40. if (noVerify)
  41. reslove(res.data, res);
  42. else if (res.data.code == 200)
  43. reslove(res.data, res);
  44. else if ([401, 110003, 110004].indexOf(res.data.code) !== -1) {
  45. toLogin();
  46. reject(res.data);
  47. } else if (res.data.code == 400) {
  48. uni.hideLoading()
  49. uni.showModal({
  50. title: i18n.t(`提示`),
  51. content: res.data.msg,
  52. showCancel: false,
  53. confirmText: i18n.t(`我知道了`)
  54. });
  55. } else
  56. reject(res.data.msg || i18n.t(`系统错误`));
  57. },
  58. fail: (msg) => {
  59. let data = {
  60. mag: i18n.t(`请求失败`),
  61. status: 1 //1没网
  62. }
  63. // #ifdef APP-PLUS
  64. reject(data);
  65. // #endif
  66. // #ifndef APP-PLUS
  67. reject(i18n.t(`请求失败`));
  68. // #endif
  69. }
  70. })
  71. });
  72. }
  73. const request = {};
  74. ['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
  75. request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
  76. });
  77. export default request;