/** * ajax请求相关的服务 */ import spiServiceUrl from './ajax.env' import corServiceUrl from './config.env' import { msg } from '@/utils/util' class AjaxService { constructor() { this.name = 'AjaxService' } getBaseUrl (url = '') { return url.indexOf('://') > -1 ? url : url } getHeaders({ header = {} }) { const REV_TOKEN_ENV = uni.getStorageSync('token') ? uni.getStorageSync('token') : 'X-token'; const REV_COOKIE_ENV = uni.getStorageSync('sessionid') ? uni.getStorageSync('sessionid') : 'sessionid'; header['Accept'] = 'application/json' header['Content-Type'] = 'application/x-www-form-urlencoded' header['X-Token'] = REV_TOKEN_ENV header['cookie'] = REV_COOKIE_ENV return header } request(options = {}) { let header = this.getHeaders(options) let url = this.getBaseUrl(options.url) if (options.header) { header = Object.assign(header, options.header) } if(options.isHost){ url = corServiceUrl + url }else{ url = spiServiceUrl + url } let { isLoading = true } = options if (isLoading) { wx.showLoading({ title: '加载中' }) } const requestPromise = new Promise((resolve, reject) => { uni.request({ url: url, method: options.method || 'POST', data: options.data || {}, header, success: res => { if (isLoading) wx.hideLoading(); if(options.isStatus){ resolve(res.data) }else{ if (res.data.code === 0) { resolve(res.data) } else { reject(res.data) } } }, fail: error => { reject(error) wx.hideLoading() } }) }) return requestPromise } get(options) { options.method = 'GET' return this.request(options) } post(options) { options.method = 'POST' return this.request(options) } } export default new AjaxService()