在我们开发过程中,经常需要附带一个token,所以这里把token单独抽取出来。 可能我们的接口都是以某一个特定的前缀开始的,比如 /api, 所以我们可以提取一个baseUrl,这样后面的请求中就可以不用每次都加上前缀了,而且后期修改也简单,只需要改一下配置文件就可以。 对于后台放回的数据,我们一般会用code来标记是否操作成功。这里可以做一个统一的错误处理,所以这里添加了一个拦截器数组,可以配置多个拦截器。 然后就是对方法的封装,首先写一个request方法来封装wx.request方法。然后再分别封装get、post、put、delete方法,使用的时候直接调用这几个方法就可以。 对于header、token、interceptor、baseUrl的配置方法,我们可以直接返回this实现链式调用。 具体的在使用的时候,可以现在App.js的onLaunch方法中配置req。 import req from '../../utils/Request.js'
configReq(){ //配置baseUrl和拦截器,baseUrl例如 /api req.baseUrl(config.serverUrl) .interceptor(res=>{ switch(res.data.code){ case 401: wx.showToast({ icon: 'loading', title: '重新登录', }) this.login() return false; case 0: return true; default: wx.showToast({ title: '操作失败', }) return false; } }) },
在登录后设置token req.token(token)
具体的网络请求方法如下: req.post('/goods',data,header) .then(res=>res.data.data) .then(data=>{ wx.showToast({ title:'创建成功' }) })
代码: const METHOD={ GET:'GET', POST:'POST', PUT:'PUT', DELETE:'DELETE' } class Request{ _header={ token:null } _baseUrl=null
interceptors = []
constructor(){ const token=wx.getStorageSync('token') if(token){ this._header.token=token } }
intercept(res){ return this.interceptors .filter(f=> typeof f === 'function') .every(f=> f(res)) }
request({url,method,header={},data}){ return new Promise((resolve,reject)=>{ wx.request({ url: (this._baseUrl || '')+url, method: method || METHOD.GET, data: data, header: { ...this._header, ...header }, success: res=>this.intercept(res) && resolve(res), fail:reject }) }) }
get(url,data,header){ return this.request({url,method:METHOD.GET,header,data}) } post(url,data,header){ return this.request({url,method:METHOD.POST,header,data}) } put(url,data,header){ return this.request({url,method:METHOD.PUT,header,data}) } delete(url,data,header){ return this.request({url,method:METHOD.DELETE,header,data}) }
token(token){ this._header.token=token return this } header(header){ this._header=header return this } baseUrl(baseUrl){ this._baseUrl=baseUrl return this } interceptor(f){ if(typeof f === 'function'){ this.interceptors.push
|