
./apis/request.js文件:處理一些基本類
/** * name: api.js * description: request處理基礎類 * author: 徐磊 * date: 2018-5-19 */ class request { constructor() { this._header = {} } /** * 設置統一的異常處理 */ setErrorHandler(handler) { this._errorHandler = handler; } /** * GET類型的網絡請求 */ getRequest(url, data, header = this._header) { return this.requestAll(url, data, header, 'GET') } /** * DELETE類型的網絡請求 */ deleteRequest(url, data, header = this._header) { return this.requestAll(url, data, header, 'DELETE') } /** * PUT類型的網絡請求 */ putRequest(url, data, header = this._header) { return this.requestAll(url, data, header, 'PUT') } /** * POST類型的網絡請求 */ postRequest(url, data, header = this._header) { return this.requestAll(url, data, header, 'POST') } /** * 網絡請求 */ requestAll(url, data, header, method) { return new Promise((resolve, reject) => { wx.request({ url: url, data: data, header: header, method: method, success: (res => { if (res.statusCode === 200) { //200: 服務端業務處理正常結束 resolve(res) } else { //其它錯誤,提示用戶錯誤信息 if (this._errorHandler != null) { //如果有統一的異常處理,就先調用統一異常處理函數對異常進行處理 this._errorHandler(res) } reject(res) } }), fail: (res => { if (this._errorHandler != null) { this._errorHandler(res) } reject(res) }) }) }) } } export default request

./apis/api.js文件:進行接口處理
/** * name: api.js * description: 公告接口的寫法,避免每個頁面都寫一次接口 * author: shimily * date: 2019-4-16 */ import request from './request.js' import config from '../config.js' class api { constructor() { let cityId = wx.getStorageSync('city_id'); this._baseUrl = config.notice+'?cityId='+cityId this._defaultHeader = { "access-token":config.accessToken, "version":config.version, "user-token":config.userToken, 'content-type': 'application/json' } this._request = new request this._request.setErrorHandler(this.errorHander) } /** * 統一的異常處理方法 */ errorHander(res) { console.error(res) } /** * 查詢公告 */ getNotice() { let data = {} return this._request.getRequest(this._baseUrl, data,this._defaultHeader, 'GET').then(res => res.data) } /** * 獲取所有課程 */ getCourseList(page = 1, size = 10, key = null) { let data = key != null ? { page: page, size: size, queryValue: key } : { page: page, size: size } return this._request.getRequest(this._baseUrl + '/course/mobile', data).then(res => res.data) } } export default api
根目錄下的api.js里面引入自己寫的api.js文件


每個pages頁面的使用方法
app.api.getNotice() .then(res => { if(res.code==1){ console.log('rrrr',res); }else{ console.log('該區域沒有公告'); } }).catch(res => { wx.showToast({ title: '出錯了!', icon: 'none' }) })

原文地址:https://www.jianshu.com/p/f9c1d2fde321
