http.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import store from '@/store'
  2. import config from './config'
  3. import utils from './utils'
  4. const request = (method, url, data) => {
  5. return new Promise((resolve, reject) => {
  6. uni.request({
  7. method,
  8. url: utils.isHttp(url) ? url : config.apiBaseUrl + url,
  9. header: {
  10. Authorization: store.state.token
  11. },
  12. data
  13. }).then(res => {
  14. if (res.code === 201) {
  15. store.commit('setUserInfo', {})
  16. // opt.isAuth && uni.navigateTo({
  17. // url: '/pages/login/login'
  18. // })
  19. }
  20. if (res.code === 200 || res.success) {
  21. resolve(res)
  22. } else{
  23. uni.showToast({
  24. title: res.msg,
  25. icon: 'none'
  26. })
  27. reject(res)
  28. }
  29. }).catch(err => {
  30. reject(err)
  31. }).finally(() => {
  32. uni.hideLoading()
  33. })
  34. })
  35. }
  36. const http = {}
  37. const methods = ['GET', 'POST', 'PUT', 'DELETE']
  38. methods.forEach(method => {
  39. http[method.toLowerCase()] = (url, data, options) => {
  40. const loadingTitle = method === 'GET' ? '加载中...' : '提交中...'
  41. const opt = Object.assign({}, config.httpDefaultOption, { loadingTitle }, options)
  42. if (opt.isAuth) {
  43. if (!store.state.token) {
  44. // uni.navigateTo({
  45. // url: '/pages/login/login'
  46. // })
  47. // return Promise.reject({
  48. // msg: '无token'
  49. // })
  50. }
  51. }
  52. opt.showLoading && uni.showLoading({
  53. title: opt.loadingTitle
  54. })
  55. return request(method, url, data)
  56. }
  57. })
  58. export default http