React Native实战系列第十一篇——网络请求
2017-05-22 本文已影响449人
撩课_叶建华
前言
- 我们使用的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和资料发放!