自己封裝的uni-app服務(wù)端請求,包括 異常捕獲、loading開啟關(guān)閉、特殊請求基礎(chǔ)地址、header的token配置、請求編碼為application/json或application/x-www-form-urlencoded
http.js
// created by wangyong for uni-app request 2019.11.22
const baseURL = 'http://localhost:8888/vec';
const http = (options) => {
return new Promise((resolve, reject) => {
uni.showLoading({
title: '加載中...',
mask: options.load || false // 默認(rèn)遮罩出現(xiàn)可以繼續(xù)操作
});
try{
uni.request({
url: (options.baseURL || baseURL) + options.url,
method: options.method || 'POST', // 默認(rèn)為POST請求
data: options.data, //請求超時(shí)在manifest.json配置
header: {
'v-token': '333333',
'Content-Type': options.header == 'form' ? 'application/x-www-form-urlencoded' : 'application/json'
},
success: res => {
resolve(res.data)
},
fail: (err) => {
reject(err.data);
console.log(err);
uni.showToast({
title: '請檢查網(wǎng)絡(luò)連接',
icon: 'none'
})
/*錯(cuò)誤碼處理
let code = err.data.code;
switch (code) {
case 1000:
break;
default:
break;
} */
},
complete: () => {
uni.hideLoading();
}
});
}catch(e){
uni.hideLoading();
uni.showToast({
title: '服務(wù)端異常',
icon: 'none'
})
}
})
}
export default http
main.js 添加
import http from './common/http.js'
Vue.prototype.$HTTP = http
調(diào)用實(shí)例:
this.$HTTP({
method: 'POST',
url: '/api/news',
data: {},
// baseURL:'http://www.buwang.com'
// header:'form'
}).then((res) =>{
console.log(res)
}
// (err)=>{ console.log(err) }
)