原生的uni.requestAPI有promise形式,網上也有uni-request封裝模仿axios(我在調用的時候出了問題,還沒找到原因)
在基於以下情況決定自己封裝
- 有baseUrl
- 有時請求
header中的content-type
為application/x-www-form-urlencoded
- 登錄后調用接口header中需要塞token
- 在調用接口前對數據可以進行統一處理,比如刪除值為null的屬性
- 在調用接口后某些數據屬性為null,在uni app中template里放值為null的屬性會顯示undefined,可以統一轉成無數據
- 加載狀態(?感覺有點不合理,用promise.all解決好像更好)
在項目目錄static的js文件下的新建url.js
function request(url, data, method = 'get', contentType = 1) { let header = { 'content-type':contentType === 1 ? 'application/json' : 'application/x-www-form-urlencoded', Authorization:uni.getStorageSync('authorization') != ''?uni.getStorageSync('authorization'):null } for (let property in data) { if (data[property] == null) { delete data[property] } } return new Promise((resolve, reject) => { uni.request({ url: baseUrl + url, data, method, header, success: (res) => { if (res.statusCode == 200) { resolve(res) } else if (res.statusCode == 405) { uni.showToast({ icon: 'none', title: '請求方法錯誤', duration: 1500 }); } else if (res.statusCode == 401) { uni.showToast({ icon: 'none', title: '未登錄或登錄狀態已超時', duration: 1500 }); setTimeout(() => { uni.reLaunch({ url: '/pages/me/user/user', }); }, 1500) store.commit('logout') } else { uni.showToast({ icon: 'none', title: '請求錯誤:' + res.statusCode, duration: 1500 }); } }, fail: (err) => { console.log('request fail', err) uni.showToast({ icon: 'none', title: err.errMsg, duration: 2000 }); reject(err) } }) }) }
export暴露后,在main.js中直接掛載在vue上
import { request, urlList } from './common/url.js' Vue.prototype.$http= request
Vue.prototype.$urlList = urlList
頁面中的使用:
this.$http(this.$urlList.login, param, 'post').then(res => { if (res.data.success) { } else { } })
如果content-type有其他的自己在方法中配置其他的