http.js 1.8 KB

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