React Native 使用Fetch发送网络请求的示例代码
我们在项目中经常会用到HTTP请求来访问网络,HTTP(HTTPS)请求通常分为"GET"、"PUT"、"POST"、"DELETE",如果不指定默认为GET请求。
在项目中我们常用到的一般为GET和POST两种请求方式,针对带参数的表单提交这类的请求,我们通常会使用POST的请求方式。
为了发出HTTP请求,我们需要使用到ReactNative提供的FetchAPI来进行实现。要从任意地址获取内容的话,只需简单地将网址作为参数传递给fetch方法即可(fetch这个词本身也就是获取的意思
GET
如果你想要通过GET方法去请求数据并转化成JSON,可以通过如下代码实现:
fetch('https://facebook.github.io/react-native/movies.json')
.then((response)=>response.json())
.then((responseJson)=>{
returnresponseJson.movies;
})
.catch((error)=>{
console.error(error);
});
通过上面的请求把返回的Response转化成JSONObject,然后取出JSONObject里的movies字段。同时,如果发生Error,如网络不通或访问连接错误等,会被.catch。在正常的情况下,我们可以得到如下结果:
{
"title":"TheBasics-Networking",
"description":"Yourappfetchedthisfromaremoteendpoint!",
"movies":[
{"title":"StarWars","releaseYear":"1977"},
{"title":"BacktotheFuture","releaseYear":"1985"},
{"title":"TheMatrix","releaseYear":"1999"},
{"title":"Inception","releaseYear":"2010"},
{"title":"Interstellar","releaseYear":"2014"}
]
}
POST(一)
当然,上面是最基本的GET请求,Fetch还有可选的第二个参数,可以用来定制HTTP请求一些参数。你可以指定Headers参数,或是指定使用POST方法,又或是提交数据等等:FetchAPI还支持自定义Headers,更换Method,添加Body等。
leturl="http://www.yousite.com/xxxx.ashx”
letparams={"name":"admin","password":"admin"};
fetch(url,{
method:'POST',
headers:{
'Accept':'application/json',
'Content-Type':'application/json',
},
body:JSON.stringify(params)
})
上面构建了一个基本的POST请求,添加了自己的Headers:Accept和Content-Type,添加了Body。
POST(二)
leturl="http://www.yousite.com/xxxx.ashx”;
letparams="username=admin&password=admin”;
fetch(url,{
method:'POST',
headers:{
'Content-Type':'application/x-www-form-urlencoded'
},
body:params,
}).then((response)=>{
if(response.ok){
returnresponse.json();
}
}).then((json)=>{
console.log(json)
}).catch((error)=>{
console.error(error);
});
POST(三)推荐
通过上面两种方法,我们还有一种方式可以发送POST请求,当然这种方式也是被推荐使用的。
如果你的服务器无法识别上面POST的数据格式,那么可以尝试传统的form格式,示例如下:
letREQUEST_URL='http://www.yousite.com/xxxx.ashx';
//`首先我们需要自己创建一个FormData,来存请求参数`
letparameters=newFormData();
parameters.append("mt","30013");
parameters.append("pg","1");
parameters.append('ps','20');
fetch(REQUEST_URL,{
method:'POST',
body:parameters
}).then(
(result)=>{
if(result.ok){
console.log(result)
result.json().then(
(obj)=>{
console.log(obj)
}
)
}
}
).catch((error)=>{
console.log(error)
Alert.alert('Error')
})
推荐这种方法的好处还有一个,就是可以在FormData中直接传递字节流实现上传图片的功能,代码如下:
uploadImage(){
letformData=newFormData();
letfile={uri:uri,type:'multipart/form-data',name:'a.jpg'};
formData.append("images",file);
fetch(url,{
method:'POST',
headers:{
'Content-Type':'multipart/form-data',
},
body:formData,
})
.then((response)=>response.text())
.then((responseData)=>{
console.log('responseData',responseData);
})
.catch((error)=>{console.error('error',error)});
}
处理服务器的响应数据
上面的例子演示了如何发起请求。很多情况下,你还需要处理服务器回复的数据。
网络请求天然是一种异步操作,Fetch方法会返回一个Promise,这种模式可以简化异步风格的代码,关于Promise,请参考:Promise
处理服务器返回的数据,我们已经在上面第二种和第三种的POST请求中实现了数据的处理。具体代码参考上面的实现代码。
默认情况下,iOS会阻止所有非https的请求。如果你请求的接口是http协议,那么首先需要添加一个AppTransportSecurity的例外。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。