http.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. //const ip = 'http://127.0.0.1:9191';
  2. const ip = 'https://chenglantimes.com/prod-api';
  3. //const ip = 'http://192.168.1.21:9191';
  4. /**
  5. * 封装的http请求
  6. */
  7. const request = (opt) => {
  8. opt = opt || {};
  9. opt.url = opt.url || '';
  10. opt.data = opt.data || null;
  11. opt.method = opt.method || 'GET';
  12. opt.contentType = opt.contentType || 'application/json;charset=UTF-8'
  13. opt.header = opt.header || {
  14. "Content-Type": opt.contentType,
  15. "Authorization": getUser().token ? getUser().token : ''
  16. };
  17. opt.loading = opt.loading || 'true';
  18. opt.success = opt.success || function () {};
  19. opt.fail = opt.fail || function () {};
  20. // console.log("**************************************参数调式***************************************************");
  21. // console.log("请求地址:" + opt.url + " 请求参数:" + JSON.stringify(opt.data));
  22. // console.log("************************************************************************************************");
  23. if (opt.loading == 'true') {
  24. uni.showLoading({
  25. title: '正在加载',
  26. mask: true
  27. });
  28. }
  29. uni.request({
  30. url: ip + opt.url,
  31. data: opt.data,
  32. method: opt.method,
  33. header: opt.header,
  34. dataType: 'json',
  35. success: res => {
  36. setTimeout(() => {
  37. uni.hideLoading();
  38. }, 500)
  39. /*******************未授权或未登录***************************/
  40. if (res.data.code === 401 || res.data.code === 403) {
  41. uni.showModal({
  42. title: '提示',
  43. content: res.data.msg,
  44. showCancel: false,
  45. success: () => {
  46. uni.removeStorageSync('user');
  47. if (res.data.code === 401) {
  48. uni.navigateTo({
  49. url: '/pages/user/login'
  50. })
  51. }
  52. opt.fail();
  53. return;
  54. }
  55. });
  56. return;
  57. }
  58. /*******************系统内部错误***************************/
  59. if (res.data.code === 500 || res.data.status === 404) {
  60. uni.showModal({
  61. content: res.data.msg || res.data.message,
  62. showCancel: false
  63. });
  64. opt.fail(res);
  65. return;
  66. }
  67. opt.success(res);
  68. },
  69. fail: e => {
  70. uni.hideLoading();
  71. uni.getNetworkType({
  72. success: res => {
  73. if (res.networkType == 'none') {
  74. uni.showModal({
  75. content: '当前网络不可用,请检查网络稍后重试',
  76. showCancel: false
  77. });
  78. } else {
  79. uni.showModal({
  80. content: '服务异常,请稍后重试',
  81. showCancel: false
  82. })
  83. }
  84. }
  85. });
  86. }
  87. })
  88. }
  89. const getUser = () => {
  90. return uni.getStorageSync('user');
  91. }
  92. module.exports = {
  93. ip: ip,
  94. request,
  95. getUser
  96. };