ajax.service.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * ajax请求相关的服务
  3. */
  4. import baseUrl from './config.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 { isLoading = true } = options
  29. if (isLoading) {
  30. wx.showLoading({ title: '加载中' })
  31. }
  32. const requestPromise = new Promise((resolve, reject) => {
  33. uni.request({
  34. url: url,
  35. method: options.method || 'POST',
  36. data: options.data || {},
  37. header,
  38. success: res => {
  39. if (isLoading) wx.hideLoading();
  40. if(options.isStatus){
  41. resolve(res.data)
  42. }else{
  43. if (res.data.code === 0) {
  44. resolve(res.data)
  45. } else {
  46. reject(res.data)
  47. }
  48. }
  49. },
  50. fail: error => {
  51. reject(error)
  52. wx.hideLoading()
  53. }
  54. })
  55. })
  56. return requestPromise
  57. }
  58. get(options) {
  59. options.method = 'GET'
  60. return this.request(options)
  61. }
  62. post(options) {
  63. options.method = 'POST'
  64. return this.request(options)
  65. }
  66. }
  67. export default new AjaxService()