ajax.service.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. getHeaders({ header = {} }) {
  14. const REV_TOKEN_ENV = uni.getStorageSync('token') ? uni.getStorageSync('token') : 'X-token';
  15. const REV_COOKIE_ENV = uni.getStorageSync('sessionid') ? uni.getStorageSync('sessionid') : 'sessionid';
  16. header['Accept'] = 'application/json'
  17. header['Content-Type'] = 'application/x-www-form-urlencoded'
  18. header['X-Token'] = REV_TOKEN_ENV
  19. header['cookie'] = REV_COOKIE_ENV
  20. return header
  21. }
  22. request(options = {}) {
  23. let header = this.getHeaders(options)
  24. if (options.header) {
  25. header = Object.assign(header, options.header)
  26. }
  27. let url = this.getBaseUrl(options.url)
  28. let {
  29. isLoading = true
  30. } = options
  31. if (isLoading) {
  32. wx.showLoading({ title: '加载中' })
  33. }
  34. const requestPromise = new Promise((resolve, reject) => {
  35. uni.request({
  36. url: url,
  37. method: options.method || 'POST',
  38. data: options.data || {},
  39. header,
  40. success: res => {
  41. if (isLoading) wx.hideLoading();
  42. if (res.data.code === 0) {
  43. resolve(res.data)
  44. } else {
  45. reject(res.data)
  46. }
  47. },
  48. fail: error => {
  49. reject(error)
  50. wx.hideLoading()
  51. }
  52. })
  53. })
  54. return requestPromise
  55. }
  56. get(options) {
  57. options.method = 'GET'
  58. return this.request(options)
  59. }
  60. post(options) {
  61. options.method = 'POST'
  62. return this.request(options)
  63. }
  64. }
  65. export default new AjaxService()