前言
- 我們使用的APP都需要從服務器上獲取數據,那么就必須要請求網絡數據,在React-Native中可以用ajax去請求網絡數據,但更多情況下是采用fetch API。
一、fetch發送get請求
- fetch發送get請求
fetch(http://192.168.0.138:3000/data.json) // 1.發送請求
.then((response)=>response.json()) // 2. 把數據轉成json
.then((responseJson)=>{
// 3. 根據數據處理UI界面
})
.catch((error)=>{
// 4. 捕獲到錯誤異常時調用
})
fetch發送請求,如果沒有設置請求方式,默認是get請求;
then用于函數回調,當上一操作完成后,就會自動執行then的回調函數,并且自動把處理完的結果,作為參數傳遞給then的回調函數。
get請求簡單封裝
module.exports = {
/**
* GET請求
* @param {請求路徑} api_url
* @param {參數列表} param
* @param {成功回調} successBack
* @param {失敗回調} failureBack
*/
GET:(api_url, param, successBack, failureBack)=>{
// 1. 參數拼接總串, 拼接操作符, 索引
var allParamStr = ' ', flag = '?', index = 0;
// 2. 把json對象轉成字符串
var jsonStr = JSON.stringify(param);
if (jsonStr !== undefine || jsonStr !== '{}') { // 過濾
for (key in param){
if (index > 0) {
flag = '&'
}
allParamStr += mark + flag + '=' + param[key];
index++;
}
}
// 3.拼接參數
api_url += totalParamStr;
fetch(api_url)
.then((response)=>response.json())
.then((responseJson)=>{ // 成功回調
successBack(responseJson);
})
.catch((error)=>{ // 失敗回調
failureBack(error);
})
}
};
<p></p>
<p></p>
<p></p>
<p></p>
二、fetch發送post請求
- fetch發送post請求
fetch('http://192.168.0.138:3000/userlogin/', {
method: 'POST', // 請求方式
headers: { // 請求頭
'Accept': 'application/json', // 接收的是json格式數據
'Content-Type': 'application/json',
},
body: JSON.stringify({ // 把json對象轉成字符串
firstParam: 'yourValue', // 要傳遞的參數
secondParam: 'yourOtherValue',
})
})
- application/json請求,案例簡單實操
module.exports = {
Post(){
fetch('http://192.168.0.138:3000/userlogin',{
method:'POST',
headers:{
'Content-Type':'application/json' // 不能寫錯
},
body:JSON.stringify({ // 把json對象轉成字符串
name: 'xzh',
pwd: '12306',
})
})
.then((response)=>response.json())
.then((json)=>{
console.log(json)
})
.catch((error)=>{
console.log(error)
})
}
}
- POST請求簡單封裝
module.exports = {
/**
* POST請求
* @param {請求路徑} api_url
* @param {參數列表} param
* @param {成功回調} success
* @param {失敗回調} failure
*/
POST(api_url, param, success, failure) {
fetch(api_url,{
method:'POST',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify(param)
})
.then((response)=>response.json())
.then((responseJson)=>{
success(responseJson);
})
.catch((error)=>{
failure(error);
})
}
}
<p></p>
<p></p>
<p></p>
<p></p>
長按圖片-->識別圖中二維碼
近期正在把公眾賬號的文章轉移到簡書,如果要了解第一動態,請關注我的微信公眾賬號,帶你從零到一的進行React Native開發實戰,在其他文章中會有對應的code和資料發放!