http.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { noEmpty } from '@utils'
  2. const Http = (options = { data: {} }) => {
  3. return new Promise((resolve, reject) => {
  4. if (options.loadingStr === 'loading') {
  5. uni.showLoading({
  6. mask: true,
  7. title: '加载中..'
  8. })
  9. }
  10. let token = uni.getStorageSync('MD_token') || ''
  11. let header = {
  12. 'Content-Type': 'application/json',
  13. 'token': token,
  14. // 'Content-Type': 'application/x-www-form-urlencoded'
  15. }
  16. let params = {...options.data}
  17. if (uni.getStorageSync('APP_token')) params.token = uni.getStorageSync('APP_token')
  18. for (let key in options.data) {
  19. if (options.data[key] === undefined || options.data[key] === 'undefined') {
  20. params[key] = ''
  21. }
  22. }
  23. let url = uni.baseUrl + options.url
  24. // let url = options.url
  25. if (options.queryData) {
  26. let qStr = ''
  27. for(let k in options.queryData) {
  28. qStr += `${k}=${options.queryData[k]}&`
  29. }
  30. qStr = qStr.substr(0, qStr.length - 1)
  31. url += `?${qStr}`
  32. }
  33. uni.request({
  34. url,
  35. data: {
  36. ...params
  37. },
  38. header,
  39. method: options.method || 'POST',
  40. complete: res => {
  41. if (options.loadingStr === 'loading') {
  42. uni.hideLoading()
  43. }
  44. },
  45. success: res => {
  46. const { data: cData } = res
  47. const code = cData.errno
  48. switch (code) {
  49. case 0:
  50. return resolve(noEmpty(cData.data) ? cData.data : cData)
  51. break
  52. case 401:
  53. case 404:
  54. case 405:
  55. uni.removeStorageSync('MD_userInfo')
  56. uni.removeStorageSync('MD_token')
  57. uni.navigateTo({
  58. url: '/pages/user/login/login'
  59. })
  60. break
  61. default:
  62. uni.showModal({
  63. title: '提示',
  64. content: `${cData.errmsg}(${code})`,
  65. })
  66. return reject(cData)
  67. }
  68. // resolve()
  69. },
  70. fail: err => {
  71. console.log(err)
  72. reject(err)
  73. }
  74. })
  75. })
  76. }
  77. // export default Http
  78. function request (url, data, loadingStr, queryData) {
  79. return Http({
  80. url,
  81. data,
  82. loadingStr,
  83. queryData,
  84. })
  85. }
  86. export {
  87. request,
  88. }