class request { static BASE_URL = 'https://llzlovesh.top/api/' static constructor() { this._header = { "Content-Type": "application/json", "token": wx.getStorageSync('token') } } /** * 设置统一的异常处理 */ static setErrorHandler(handler) { this._errorHandler = handler } /** * GET类型的网络请求 */ static getRequest(url, data, header = this._header ) { return this.requestAll(url, data, header, 'GET') } /** * DELETE类型的网络请求 */ static deleteRequest(url, data, header = this._header ) { return this.requestAll(url, data, header, 'DELETE') } /** * PUT类型的网络请求 */ static putRequest(url, data, header = this._header ) { return this.requestAll(url, data, header, 'PUT') } /** * POST类型的网络请求 */ static postRequest(url, data, header = this._header) { return this.requestAll(url, data, header, 'POST') } static upload(url, name, path, ortherData, header){ return new Promise((resolve, reject) => { wx.uploadFile({ url: url, header: header, filePath: path, name: name, formData: ortherData, success: (res => { res.data = JSON.parse(res.data); if (res.data.code === 1) { //200: 服务端业务处理正常结束 resolve(res.data) } else { if (res.data.code === 0){ wx.showToast({ title: res.data.message, }) } //其它错误,提示用户错误信息 if (this._errorHandler != null) { //如果有统一的异常处理,就先调用统一异常处理函数对异常进行处理 this._errorHandler(res) } reject(res) } }), fail: (res => { if (this._errorHandler != null) { this._errorHandler(res) } wx.showToast({ title: '网络异常请,稍后再试~', }) reject(res) }) }) }) } /** * 网络请求 */ static requestAll(url, data, header, method) { const _self = this wx.showLoading() return new Promise((resolve, reject) => { wx.request({ url: url, data: data, header: header, method: method, success: (res => { wx.hideLoading() if (res.data.code === 1) { //200: 服务端业务处理正常结束 resolve(res.data) } else { if (res.data.code === 0){ wx.showToast({ title: res.data.message, }) } if (res.data.code === 901){ console.log(res.data) } //其它错误,提示用户错误信息 if (this._errorHandler != null) { //如果有统一的异常处理,就先调用统一异常处理函数对异常进行处理 this._errorHandler(res) } reject(res) } }), fail: (res => { if (this._errorHandler != null) { this._errorHandler(res) } wx.showToast({ title: '网络异常请,稍后再试~', }) reject(res) }) }) }) } } export default request