http copy.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. var common = require('./common.js');
  2. var storage = require('./storage.js');
  3. var config = require('./config.js');
  4. // 检查token是否失效 如失效 清除缓存 提示重新登录
  5. // 402: 解析token出错 403: token格式错误 404: 公共声明中缺少必要字段 405: token验证失败
  6. function _checkTokenValid(res) {
  7. if (
  8. res.data.code === 402 ||
  9. res.data.code === 403 ||
  10. res.data.code === 404 ||
  11. res.data.code === 405 ||
  12. res.data.code === 300 ||
  13. res.data.code === 302 ||
  14. res.data.code === 303 ||
  15. res.data.code === 304 ||
  16. res.data.code === 305 ||
  17. res.data.code === 306
  18. ) {
  19. uni.clearStorageSync();
  20. uni.reLaunch({
  21. url: '/pages/login/login'
  22. });
  23. // wx.navigateTo({
  24. // url: '/pages/login/login',
  25. // })
  26. // wx.showModal({
  27. // title: '错误',
  28. // content: '鉴权认证过期,请重新登录',
  29. // showCancel: false
  30. // })
  31. return false;
  32. }
  33. return true;
  34. }
  35. function getRequest(url, data, successCallBack, failCallBack) {
  36. if (!failCallBack) {
  37. failCallBack = function () {};
  38. }
  39. if (url.indexOf('?') > 0) {
  40. url = url + '&' + common.obj2UrlQuery(data);
  41. } else {
  42. url = '?' + common.obj2UrlQuery(data);
  43. }
  44. uni.request({
  45. url: url + '?token=' + storage.getApiToken(),
  46. method: 'GET',
  47. success: function (res) {
  48. uni.hideLoading();
  49. if (_checkTokenValid(res)) {
  50. successCallBack(res);
  51. }
  52. },
  53. fail: function (res) {
  54. uni.hideLoading();
  55. uni.showModal({
  56. title: '错误',
  57. content: '网络错误',
  58. showCancel: false
  59. });
  60. if (failCallBack) {
  61. failCallBack(res);
  62. }
  63. }
  64. });
  65. }
  66. function postRequest(url, data, successCallBack, failCallBack) {
  67. if (!failCallBack) {
  68. failCallBack = function () {};
  69. }
  70. uni.request({
  71. url: url + '?token=' + storage.getApiToken(),
  72. data: data,
  73. header: {
  74. 'content-type': 'application/json'
  75. },
  76. method: 'POST',
  77. success: function (res) {
  78. //wx.hideLoading();
  79. if (_checkTokenValid(res)) {
  80. successCallBack(res);
  81. }
  82. },
  83. fail: function (res) {
  84. uni.hideLoading();
  85. failCallBack(res);
  86. }
  87. });
  88. }
  89. function getApi(url, data, successCallBack, failCallBack) {
  90. getRequest(url, data, successCallBack, failCallBack);
  91. }
  92. function postApi(url, data, successCallBack, failCallBack) {
  93. postRequest(url, data, successCallBack, failCallBack);
  94. }
  95. module.exports = {
  96. getRequest: getRequest,
  97. postRequest: postRequest,
  98. getApi: getApi,
  99. postApi: postApi
  100. };