./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' }) })