http.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. })
  9. uni.request({
  10. method,
  11. url: utils.isHttp(url) ? url : config.apiBaseUrl + url,
  12. header: {
  13. 'content-type': 'application/x-www-form-urlencoded',
  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', {})
  23. // opt.isAuth && uni.navigateTo({
  24. // url: '/pages/login/login'
  25. // })
  26. }
  27. if (data.code === 200 || data.success) {
  28. resolve(data)
  29. } else{
  30. uni.showToast({
  31. title: data.msg,
  32. icon: 'none'
  33. })
  34. reject(data)
  35. }
  36. }).catch(err => {
  37. opt.showLoading && uni.hideLoading()
  38. reject(err)
  39. })
  40. })
  41. }
  42. const http = {}
  43. const methods = ['GET', 'POST', 'PUT', 'DELETE']
  44. methods.forEach(method => {
  45. http[method.toLowerCase()] = (url, data, options) => {
  46. const loadingTitle = method === 'GET' ? '加载中...' : '提交中...'
  47. const opt = Object.assign(
  48. { loadingTitle },
  49. config.httpDefaultOption,
  50. options
  51. )
  52. if (opt.isAuth) {
  53. if (!store.state.token) {
  54. // uni.navigateTo({
  55. // url: '/pages/login/login'
  56. // })
  57. // return Promise.reject({
  58. // msg: '无token'
  59. // })
  60. }
  61. }
  62. return request(method, url, data, opt)
  63. }
  64. })
  65. export default http