http.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { useUserStore } from '@/stores/user'
  2. import config from './config'
  3. import utils from './utils'
  4. const request = (method, url, data, opt) => {
  5. const userStore = useUserStore()
  6. return new Promise((resolve, reject) => {
  7. opt.showLoading && uni.showLoading({
  8. title: opt.loadingTitle,
  9. mask: method === 'POST' ? true : false
  10. })
  11. uni.request({
  12. method,
  13. url: utils.isHttp(url) ? url : config.apiBaseUrl + url,
  14. header: {
  15. Authorization: userStore.token,
  16. ...opt.header
  17. },
  18. data
  19. }).then(res => {
  20. opt.showLoading && uni.hideLoading()
  21. const data = res.data
  22. if (data.code === 201) {
  23. userStore.setUserInfo({})
  24. userStore.setToken('')
  25. // opt.isAuth && uni.navigateTo({
  26. // url: '/pages/login/login'
  27. // })
  28. }
  29. if (data.code === 200 || data.success) {
  30. resolve(data)
  31. } else {
  32. opt.showErrorMsg && uni.showToast({
  33. title: data.msg,
  34. icon: 'none'
  35. })
  36. reject(data)
  37. }
  38. }).catch(err => {
  39. opt.showLoading && uni.hideLoading()
  40. reject(err)
  41. })
  42. })
  43. }
  44. const http = {}
  45. const methods = ['GET', 'POST', 'PUT', 'DELETE']
  46. methods.forEach(method => {
  47. http[method.toLowerCase()] = (url, data, options) => {
  48. const loadingTitle = method === 'GET' ? '加载中...' : '提交中...'
  49. const opt = Object.assign({
  50. loadingTitle
  51. },
  52. config.httpDefaultOption,
  53. options
  54. )
  55. if (opt.isAuth) {
  56. const userStore = useUserStore()
  57. if (!userStore.token) {
  58. // uni.navigateTo({
  59. // url: '/pages/login/login'
  60. // })
  61. // return Promise.reject({
  62. // msg: '无token'
  63. // })
  64. }
  65. }
  66. // 提交数据中值为undefined的改成空字符串
  67. if (typeof data === 'object') {
  68. for (let key in data) {
  69. if (data[key] === 'undefined') {
  70. data[key] = ''
  71. }
  72. }
  73. }
  74. return request(method, url, data, opt)
  75. }
  76. })
  77. export default http