http.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. //const ip = 'http://127.0.0.1:9191';
  2. //const ip = 'https://chenglantimes.com/prod-api';
  3. const ip = 'http://192.168.0.105: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) {
  41. uni.removeStorageSync('user');
  42. uni.navigateTo({
  43. url: '/pages/user/login'
  44. })
  45. return;
  46. }
  47. /*******************系统内部错误***************************/
  48. if (res.data.code === 500 || res.data.status === 404) {
  49. uni.showModal({
  50. content: res.data.msg || res.data.message,
  51. showCancel: false
  52. });
  53. opt.fail(res);
  54. return;
  55. }
  56. opt.success(res);
  57. },
  58. fail: e => {
  59. uni.hideLoading();
  60. uni.getNetworkType({
  61. success: res => {
  62. if (res.networkType == 'none') {
  63. uni.showModal({
  64. content: '当前网络不可用,请检查网络稍后重试',
  65. showCancel: false
  66. });
  67. } else {
  68. uni.showModal({
  69. content: '服务异常,请稍后重试',
  70. showCancel: false
  71. })
  72. }
  73. }
  74. });
  75. }
  76. })
  77. }
  78. const getUser = () => {
  79. return uni.getStorageSync('user');
  80. }
  81. module.exports = {
  82. ip: ip,
  83. request,
  84. getUser
  85. };