request.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. // API配置信息
  2. import urls from '../common/config.js'
  3. /**
  4. * 构建完整请求URL
  5. * @param {Object} path
  6. */
  7. function buildUrl(path) {
  8. // 完整接口地址返回
  9. if (path.startsWith('http://') || path.startsWith('https://')) {
  10. return path;
  11. }
  12. return urls.api + path;
  13. }
  14. /**
  15. * 通用请求封装
  16. * @param {Object} path
  17. * @param {Object} data
  18. */
  19. function postData(path, data) {
  20. // 构建完整请求
  21. const url = buildUrl(path)
  22. return new Promise((resolve, reject) => {
  23. uni.request({
  24. url: url,
  25. data: data,
  26. method: "POST",
  27. header: {
  28. 'content-type': "application/json",
  29. 'token': uni.getStorageSync("token")
  30. },
  31. success: function(res) {
  32. // 错误500
  33. if (res.statusCode == 500) {
  34. uni.showToast({
  35. title: '糟糕,服务器开小差了~',
  36. icon: 'none',
  37. duration: 5000
  38. });
  39. return;
  40. }
  41. // 404
  42. if (res.statusCode == 404) {
  43. uni.showToast({
  44. title: '接口地址404,请联系管理员~',
  45. icon: 'none',
  46. duration: 5000
  47. });
  48. return;
  49. }
  50. // 成功才回调
  51. if (res.data.code === 0) {
  52. resolve(res.data.data);
  53. } else {
  54. // 后台错误信息
  55. uni.showToast({
  56. title: res.data.msg,
  57. icon: 'none',
  58. duration: 3000
  59. });
  60. if (res.data.code === 10010002) {
  61. // 跳转到登录
  62. uni.navigateTo({
  63. url: '/pages/login/login'
  64. });
  65. return;
  66. }
  67. reject(res.data)
  68. }
  69. },
  70. fail: function(e) {
  71. uni.showToast({
  72. title: '啊哦,与服务器失去连接了~',
  73. icon: 'none',
  74. duration: 10000
  75. });
  76. }
  77. });
  78. });
  79. }
  80. /**
  81. * 文件上传
  82. * @param {Object} url
  83. * @param {Object} file
  84. * @param {Object} data
  85. */
  86. function uploadData(path, file, formData) {
  87. // 构建完整请求地址
  88. let url = buildUrl(path)
  89. uni.showLoading({
  90. title: '正在上传...'
  91. })
  92. // 兼容chooseMedia
  93. const filePath = file.path || file.tempFilePath
  94. return new Promise((resolve, reject) => {
  95. uni.uploadFile({
  96. url: url,
  97. filePath: filePath,
  98. name: 'file',
  99. header: {
  100. 'token': uni.getStorageSync("token")
  101. },
  102. formData: formData,
  103. success: res => {
  104. let data = {}
  105. if (res.data) {
  106. data = JSON.parse(res.data)
  107. }
  108. resolve(data);
  109. uni.hideLoading()
  110. },
  111. fail: err => {
  112. reject()
  113. uni.hideLoading()
  114. }
  115. })
  116. });
  117. }
  118. module.exports = {
  119. post: postData,
  120. upload: uploadData
  121. };