ajax.service.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * ajax请求相关的服务
  3. */
  4. import requestUrl from '@/services/config.env.js'
  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 : url
  12. }
  13. getHeaders({ header = {} }) {
  14. const REV_OPENID_ENV = uni.getStorageSync('openid') ? uni.getStorageSync('openid') : 'x-openid'
  15. header['Accept'] = 'application/json'
  16. header['Content-Type'] = 'application/x-www-form-urlencoded'
  17. header['x-openid'] = REV_OPENID_ENV
  18. return header
  19. }
  20. request(options = {}) {
  21. let header = this.getHeaders(options)
  22. let url = this.getBaseUrl(options.url)
  23. if (options.header) {
  24. header = Object.assign(header, options.header)
  25. }
  26. url = requestUrl + url
  27. let { isLoading = true } = options
  28. if (isLoading) {
  29. uni.showLoading({ title: options.loadText ? options.loadText : '加载中' })
  30. }
  31. const requestPromise = new Promise((resolve, reject) => {
  32. uni.request({
  33. url: url,
  34. method: options.method || 'POST',
  35. data: options.data || {},
  36. header,
  37. success: res => {
  38. if (isLoading) uni.hideLoading()
  39. if(options.isStatus){
  40. resolve(res.data)
  41. }else{
  42. if (res.data.code === 0) {
  43. resolve(res.data)
  44. } else {
  45. reject(res.data)
  46. }
  47. }
  48. },
  49. fail: error => {
  50. reject(error)
  51. if (isLoading) uni.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()