http.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. Authorization: store.state.token,
  14. ...opt.header
  15. },
  16. data
  17. }).then(res => {
  18. const data = res.data
  19. if (data.code === 201) {
  20. store.commit('setUserInfo', {})
  21. // opt.isAuth && uni.navigateTo({
  22. // url: '/pages/login/login'
  23. // })
  24. }
  25. if (data.code === 200 || data.success) {
  26. resolve(data)
  27. } else{
  28. uni.showToast({
  29. title: data.msg,
  30. icon: 'none'
  31. })
  32. reject(data)
  33. }
  34. }).catch(err => {
  35. reject(err)
  36. }).finally(() => {
  37. opt.showLoading && uni.hideLoading()
  38. })
  39. })
  40. }
  41. const http = {}
  42. const methods = ['GET', 'POST', 'PUT', 'DELETE']
  43. methods.forEach(method => {
  44. http[method.toLowerCase()] = (url, data, options) => {
  45. const loadingTitle = method === 'GET' ? '加载中...' : '提交中...'
  46. const opt = Object.assign(
  47. {
  48. loadingTitle,
  49. header: {
  50. 'content-type': 'application/x-www-form-urlencoded'
  51. }
  52. },
  53. config.httpDefaultOption,
  54. options
  55. )
  56. console.log(opt);
  57. if (opt.isAuth) {
  58. if (!store.state.token) {
  59. // uni.navigateTo({
  60. // url: '/pages/login/login'
  61. // })
  62. // return Promise.reject({
  63. // msg: '无token'
  64. // })
  65. }
  66. }
  67. return request(method, url, data, opt)
  68. }
  69. })
  70. export default http