http.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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', {})
  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. 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. config.httpDefaultOption,
  51. options
  52. )
  53. if (opt.isAuth) {
  54. if (!store.state.token) {
  55. // uni.navigateTo({
  56. // url: '/pages/login/login'
  57. // })
  58. // return Promise.reject({
  59. // msg: '无token'
  60. // })
  61. }
  62. }
  63. return request(method, url, data, opt)
  64. }
  65. })
  66. export default http