ajax.service.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. // msg(error)
  51. wx.hideLoading()
  52. }
  53. })
  54. })
  55. return requestPromise
  56. }
  57. get(options) {
  58. options.method = 'GET'
  59. return this.request(options)
  60. }
  61. post(options) {
  62. options.method = 'POST'
  63. return this.request(options)
  64. }
  65. }
  66. export default new AjaxService()