ajax.service.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /**
  2. * ajax请求相关的服务
  3. */
  4. import baseUrl from './ajax.env'
  5. import { msg } from '@/utils/util'
  6. class AjaxService {
  7. constructor() {
  8. this.name = 'AjaxService'
  9. }
  10. getBaseUrl (url = '') {
  11. return url.indexOf('://') > -1 ? url : baseUrl + url
  12. }
  13. getStorageUser(){
  14. let userInfo =''
  15. uni.getStorage({
  16. key: 'userInfo',
  17. success: function (res){
  18. userInfo = res.data
  19. }
  20. })
  21. return userInfo
  22. }
  23. getHeaders({ header = {} }) {
  24. const GET_LOGIN_STAUS = this.getStorageUser();
  25. console.log(GET_LOGIN_STAUS)
  26. let REV_TOKEN_ENV='';
  27. if (GET_LOGIN_STAUS != null) {
  28. REV_TOKEN_ENV = GET_LOGIN_STAUS.token
  29. }else{
  30. REV_TOKEN_ENV = 'X-token'
  31. }
  32. header['authorization'] = REV_TOKEN_ENV
  33. return header
  34. }
  35. request(options = {}) {
  36. let header = this.getHeaders(options)
  37. if (options.header) {
  38. header = Object.assign(header, options.header)
  39. }
  40. let url = this.getBaseUrl(options.url)
  41. let {
  42. isLoading = true
  43. } = options
  44. if (isLoading) {
  45. wx.showLoading({
  46. title: '加载中'
  47. })
  48. }
  49. const requestPromise = new Promise((resolve, reject) => {
  50. uni.request({
  51. url: url,
  52. method: options.method || 'POST',
  53. data: options.data || {},
  54. header,
  55. success: res => {
  56. if (isLoading) wx.hideLoading();
  57. if (res.data.code === 1) {
  58. resolve(res.data)
  59. } else {
  60. reject(res.data)
  61. }
  62. },
  63. fail: error => {
  64. reject(error)
  65. msg(error)
  66. wx.hideLoading()
  67. }
  68. })
  69. })
  70. return requestPromise
  71. }
  72. get(options) {
  73. options.method = 'GET'
  74. return this.request(options)
  75. }
  76. post(options) {
  77. return this.request(options)
  78. }
  79. }
  80. export default new AjaxService()