request.js 2.0 KB

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