? 在我們開發過程中,經常需要附帶一個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(f)
}
return this
}
}
export default new Request
export {METHOD}