微信小程序封裝的HTTP請求示例【附升級版】
本文實例講述了微信小程序封裝的HTTP請求。分享給大家供大家參考,具體如下:
微信小程序里自己封裝了請求的函數(shù),但幾乎每個頁面都要用到,所以為什么更方便的調用,再一次進行封裝。
在app.js里面定義個全局對象,這樣想要用到該函數(shù),只需要在該頁面的js文件里面,請求一個app實例。
廢話不多說,先上代碼:
//全局對象httpClient
httpClient:{
request:function(method,url,data){
//返回一個promise實例
return new Promise( (resolve,reject)=>{
wx.request({
url:url,
data:data,
mehtod:method,
success:function(res){
resolve(res)
},
fail:function(res){
reject(res);
},
complete:function(){
console.log('complete');
}
})
})
}
//get方法:用來獲取數(shù)據(jù)
get:function( url ) {
return this.request('GET',url);
},
//post方法:用來更新數(shù)據(jù)
post:function( url,data) {
resturn this.request('POST',url,data);
},
//put方法
put:function(url,data){
return this.request('PUT', url, data);
},
//delete方法
delete:function(url,data){
return this.request('DELETE', url, data);
}
在需要請求的頁面調用:
例如:登錄頁面login.js
//獲取app實例,從而調用全局對象的函數(shù)
var app=getApp();
login:function(){
var url='http:xxxxx/login';
var data={
userName:'xxxxx',
passwd:'xxxxxx'
}
app.httpClient.post( url,data )
.then( res=>{console.log("請求成功時調用該函數(shù)")})
.catch(res=>{console.log("請求失敗時調用該函數(shù)")})
}
//為了更好的閱讀,也可以將回調函數(shù),定義在外面
//這樣
loginSuccess:function(){
console.log("請求成功時調用該函數(shù)")
},
loginFail:function(){
console.log("請求失敗時調用該函數(shù)")
},
login:function(){
var self=this;
var url='http:xxxxx/login';
var data={
userName:'xxxxx',
passwd:'xxxxxx'
}
app.httpClient.post( url,data )
.then( res=>self.loginSuccess())
.catch(res=>self.loginFail())
}
是不是簡潔多了。。。。
附:升級版
上代碼
// 該函數(shù)怎么寫,需要跟后端人員協(xié)商返回的格式
function getErrorMsgByErrorNo(error_no) {
let error_msg;
switch (error_no) {
case 100: error_msg = '操作失敗,請稍后再試!'; break;
default: error_msg = '網(wǎng)絡錯誤,請稍后再試!'; break;
}
return error_msg;
}
function handleData(res) {
if (res.data.success) {
if (typeof (res.data.body) === 'string') {
return [];
} else if (Array.isArray(res.data.body) === false) {
const _arr = [];
_arr.push(res.data.body);
return _arr;
} else {
return res.data.body;
}
} else {
if (res.data.error_no) {
return {
error_no: res.data.error_no,
error_msg: getErrorMsgByErrorNo(res.data.error_no)
};
} else {
return {
error_no: 123456,
error_msg: '服務器維護中,請稍后!'
};
}
}
}
const httpClient = {
request: function (method, url, data) {
return new Promise((resolve, reject) => {
wx.request({
url: url,
data: data,
method: method,
success: function (res) {
resolve(handleData(res))
},
fail: function (err) {
console.log('request fail ', err);
resolve({
error_no: 100,
error_msg: getErrorMsgByErrorNo(100)
})
},
complete: function (res) {
console.log("request completed!");
}
})
});
},
get: function (url) {
return this.request('GET', url);
},
post: function (url, data) {
return this.request('POST', url, data);
},
put: function (url, data) {
return this.request('PUT', url, data);
},
delete: function (url, data) {
return this.request('DELETE', url, data);
},
};
module.exports = httpClient;
使用
function getMyselfData() {
const _Url= urls.url;
return httpClient.get(_Url);
}
getData() {
let resultsData = this.getMyselfData();
resultsData.then((res) => {
if (res.error_no) {
// 只要有error_no就說明請求出現(xiàn)了錯誤
this.toast.showToast({
type: 'fail',
title: res.error_msg,
})
} else {
this.setData({
journeyList: res.data
})
}
});
},
希望本文所述對大家微信小程序開發(fā)有所幫助。
相關文章
JS中for,for...in,for...of和forEach的區(qū)別和用法實例
JS遍歷數(shù)組(循環(huán)數(shù)組)的方式有多種,可以使用傳統(tǒng)的for循環(huán),也可以使用升級版的for in循環(huán),還可以使用Array類型的forEach() 方法,這篇文章主要給大家介紹了關于JS中for、for...in、for...of和forEach的區(qū)別和用法的相關資料,需要的朋友可以參考下2021-11-11
一文詳解JavaScript中的事件循環(huán)(event?loop)機制
JavaScript中的事件循環(huán)(Event?Loop)是一種重要的機制,用于管理異步代碼的執(zhí)行,它確保?JavaScript?單線程環(huán)境中的任務按照正確的順序執(zhí)行,同時允許異步操作如定時器、網(wǎng)絡請求和事件處理,本將給大家詳細的介紹一下JavaScript事件循環(huán)機制,感興趣的朋友可以參考下2023-12-12
JavaScript通過setTimeout實時顯示當前時間的方法
這篇文章主要介紹了JavaScript通過setTimeout實時顯示當前時間的方法,涉及javascript操作時間顯示的技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04
JavaScript實現(xiàn)Sleep函數(shù)的代碼
大家知道,JavaScript中沒有內置我們常用的sleep()函數(shù),只有定時器setTimeout()和循環(huán)定時器setInterval()2007-03-03

