詳解React Native網(wǎng)絡(luò)請求fetch簡單封裝
在原生應(yīng)用開發(fā)中,為了方便業(yè)務(wù)開發(fā)人員使用,我們一般會對網(wǎng)絡(luò)庫進(jìn)行一些上傳封裝,而不是直接使用,例如基于AFNetworking庫的iOS請求上層封裝,Android的諸如volley,retrofit等。在前端開發(fā)中,一般使用fetch進(jìn)行網(wǎng)絡(luò)請求,相關(guān)介紹請查看fetch示例。其實(shí)對于開發(fā)來說,系統(tǒng)提供的fetch已經(jīng)夠用了,但是為了代碼的整體結(jié)構(gòu),建議對fetch進(jìn)行簡單的Get/Post封裝。
若不封裝,我們看一下傳統(tǒng)的寫法:
fetch('http://www.pintasty.cn/home/homedynamic', {
method: 'POST',
headers: { //header
'token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiJVLTliZGJhNjBjMjZiMDQwZGJiMTMwYWRhYWVlN2FkYTg2IiwiZXhwaXJhdGlvblRpbWUiOjE0NzUxMTg4ODU4NTd9.ImbjXRFYDNYFPtK2_Q2jffb2rc5DhTZSZopHG_DAuNU'
},
body: JSON.stringify({ //參數(shù)
'start': '0',
'limit': '20',
'isNeedCategory': true,
'lastRefreshTime': '2016-09-25 09:45:12'
})
})
.then((response) => response.json()) //把response轉(zhuǎn)為json
.then((responseData) => { // 上面的轉(zhuǎn)好的json
alert(responseData); /
// console.log(responseData);
})
.catch((error)=> {
alert('錯誤了');
})
}
是不是看著有一種密集恐懼癥,并且代碼的風(fēng)格也不是很好。所以,為了方便使用,我們需要將公共的部分封裝起來,然后只需要通過參數(shù)的方式對外暴露出諸如請求Url,請求參數(shù),Header就可以了。
var HTTPUtil = {};
/**
* GET請求
*/
HTTPUtil.get = function(url, params, headers) {
if (params) {
let paramsArray = [];
//encodeURIComponent
Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
if (url.search(/\?/) === -1) {
url += '?' + paramsArray.join('&')
} else {
url += '&' + paramsArray.join('&')
}
}
return new Promise(function (resolve, reject) {
fetch(url, {
method: 'GET',
headers: headers,
})
.then((response) => {
if (response.ok) {
return response.json();
} else {
reject({status:response.status})
}
})
.then((response) => {
resolve(response);
})
.catch((err)=> {
reject({status:-1});
})
})
}
/**
* POST請求 FormData 表單數(shù)據(jù)
*/
HTTPUtil.post = function(url, formData, headers) {
return new Promise(function (resolve, reject) {
fetch(url, {
method: 'POST',
headers: headers,
body:formData,
})
.then((response) => {
if (response.ok) {
return response.json();
} else {
reject({status:response.status})
}
})
.then((response) => {
resolve(response);
})
.catch((err)=> {
reject({status:-1});
})
})
}
export default HTTPUtil;
還是上面的例子,我們怎么使用呢?
let formData = new FormData();
formData.append("id",1060);
let url='http://www.pintasty.cn/home/homedynamic';
let headers='';
HTTPUtil.post(url,formData,headers).then((json) => {
//處理 請求結(jié)果
},(json)=>{
//TODO 處理請求fail
})
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
淺析history 和 react-router 的實(shí)現(xiàn)原理
react-router 版本更新非???但是它的底層實(shí)現(xiàn)原理確是萬變不離其中,在本文中會從前端路由出發(fā)到 react-router 原理總結(jié)與分享,本文對history 和 react-router實(shí)現(xiàn)原理講解的非常詳細(xì),需要的朋友跟隨小編一起看看吧2023-08-08
react搭建在線編輯html的站點(diǎn)通過引入grapes實(shí)現(xiàn)在線拖拉拽編輯html
Grapes插件是一種用于Web開發(fā)的開源工具,可以幫助用戶快速創(chuàng)建動態(tài)和交互式的網(wǎng)頁元素,它還支持多語言和多瀏覽器,適合開發(fā)響應(yīng)式網(wǎng)頁和移動應(yīng)用程序,這篇文章主要介紹了react搭建在線編輯html的站點(diǎn)通過引入grapes實(shí)現(xiàn)在線拖拉拽編輯html,需要的朋友可以參考下2023-08-08
淺談React的React.FC與React.Component的使用
本文主要介紹了React的React.FC與React.Component的使用,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09

