request.js 1.8 KB

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