React-Native Fetch网络请求的简单封装

前端之家收集整理的这篇文章主要介绍了React-Native Fetch网络请求的简单封装前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在react-native开发中,使用Fetch进行网络请求。官方文档上的网络请求

基本使用方法

GET请求

@H_404_11@fetch(@"http://www.baidu.com") .then((response) => response.json()) .then((responseJson) => { console.log(responseJson);//打印返回的数据 }); }) .catch((error)=>{ console.log(error);//打印报的错 })

catch住fetch可能抛出的异常,否则出错时你可能看不到任何提示

POST请求

Fetch还有可选的第二个参数,可以用来定制HTTP请求一些参数。你可以指定header参数,或是指定使用POST方法,又或是提交数据等等:

@H_404_11@fetch('https://mywebsite.com/endpoint/',{ method: 'POST',headers: { 'Accept': 'application/json','Content-Type': 'application/json',},body: JSON.stringify({ firstParam: 'yourValue',secondParam: 'yourOtherValue',}) })

如果你的服务器无法识别上面POST的数据格式,那么可以尝试传统的form格式:

@H_404_11@fetch('https://mywebsite.com/endpoint/',{ method: 'POST',headers: { 'Content-Type': 'application/x-www-form-urlencoded',body: 'key1=value1&key2=value2' })

可以参考Fetch请求文档来查看所有可用的参数。

简单封装

GET

@H_404_11@/* * get请求 * url:请求地址 * params:参数 * callback:回调函数 * */ static get(url,params,callback){ if (params) { let paramsArray = []; //拼接参数 Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key])) if (url.search(/\?/) === -1) { url += '?' + paramsArray.join('&') } else { url += '&' + paramsArray.join('&') } } //fetch请求 fetch(url,{ method: 'GET',}) .then((response) => { callback(response) }) .catch((error) => { alert(error) }); }

POST

post有两种形式:

  • 第一种:’Content-Type’: ‘application/json’
@H_404_11@/* * post请求 * url:请求地址 * params:参数,这里的参数格式是:{param1: 'value1',param2: 'value2'} * callback:回调函数 * */ static postJSON(url,params,callback){ //fetch请求 fetch(url,{ method: 'POST',headers: { 'Accept': 'application/json',body:JSON.stringify(params) }) .then((response) => response.json()) .then((responseJSON) => { callback(responseJSON) }) .catch((error) => { console.log("error = " + error) }); }
  • 第二种: form表单形式
@H_404_11@/* * post请求 * url:请求地址 * params:参数,这里的参数要用这种格式:'key1=value1&key2=value2' * callback:回调函数 * */ static postForm(url,headers: { 'Content-Type': 'application/x-www-form-urlencoded',body: params }) .then((response) => response.json()) .then((responseJSON) => { callback(responseJSON) }) .catch((error) => { console.log("error = " + error) }); }

调用

@H_404_11@//post请求 let params = {'key1':'value1','key2':'value2'}; NetRequest.postJSON('http://www.baidu.com/',function (set) { //下面的就是请求来的数据 console.log(set) }) //get请求,以百度为例,没有参数,没有header NetRequest.get('https://www.baidu.com/','',function (set) { //下面是请求下来的数据 console.log(set) })

解释一下:

//将JSON数据转换成字符串
JSON.stringify(params)

//将数据JSON化 JSON.parse(responseJSON)

猜你在找的React相关文章