http.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. 'content-type': 'application/x-www-form-urlencoded',
  15. Authorization: store.state.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. store.commit('setUserInfo', null)
  24. store.commit('token', '')
  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. 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. return request(method, url, data, opt)
  65. }
  66. })
  67. export default http