美文网首页
React Native - fetch 网络请求

React Native - fetch 网络请求

作者: 黄晓坚 | 来源:发表于2017-09-27 22:52 被阅读126次

文档地址
可参考

我们使用的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.  捕获到错误异常时调用 
         })
  • 上面的示例中的init是一个对象,他里面包含了:
    • method:请求方式(GET、POST、PUT等)。
    • headers:需要用到 Headers 对象使用这个参数。
    • body:需要发送的数据
    • mode:跨域设置(cors, no-cors, same-origin)
    • cache:缓存选项(default, no-store, reload, no-cache, force- cache, or only-if-cached)

注意:

  • body:不可传对象,用JSON.stringify({...})也不可以,在jQuery 中会自动将对象封装成 formData 形式,fetch不会。

  • mode属性控制师傅跨域,其中 same-origin(同源请求,跨域会报error)、no-cors(默认,可以请求其它域的资源,不能访问response内的属性)和 cros(允许跨域,可以获取第三方数据,必要条件是访问的服务允许跨域访问)。

  • 使用 fetch 需要注意浏览器版本,但 React-Native 则不需要考虑。

  • response 对象可以有如下几种解析方式

    • arrayBuffer()
    • json()
    • text()
    • blob()
    • formData()

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);
           })
   }
};
  • 二、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);
            })
    }
}

相关文章

网友评论

      本文标题:React Native - fetch 网络请求

      本文链接:https://www.haomeiwen.com/subject/mlppextx.html