ajax.service.js 1.4 KB

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