• 【react】 react 中 前后端数据的交互方式 (原生的ajax、jq的ajax、axios、fetch )


    这是fetch  请求数据的方式


    ---fetch---基本使用

     

    一、fetch

      fetch是一种XMLHttpRequest的一种替代方案,在工作当中除了用ajax获取后台数据外我们还可以使用fetch、axios来替代ajax

     二、安装

      

      执行npm install whatwg-fetch --save即可安装。

      为了兼容老版本浏览器,还需要安装npm install es6-promise --save

    三、fetch的基本使用 

      

    复制代码
    npm install whatwg-fetch --save
    npm install es6-promise --save
    import 'es6-promise'
    import 'whatwg-fetch'
    
    fetch(url,options).then((res)=>{
      console.log(res);
    },function(err){
      console.log(err)
    })
    复制代码

    说明:

        1、fetch的返回值是一个promise对象

        2、options

            method:HTTP请求方式,默认是GET

    复制代码
       body:请求的参数
    
            fetch('/xxx', {
    
                   method: 'post',
    
                   body:'username=zhangsan&age=17'
    
     
    
           });
    复制代码

            headers:HTTP请求头

                因为一般使用JSON数据格式,所以设置ContentType为application/json

                credentials:默认为omit,忽略的意思,也就是不带cookie还有两个参数,same-origin,意思就是同源请求带cookie;include,表示无论跨域还是同源请求都会带cookie

        3、在.then里面第一个回调函数中处理response

            status(number): HTTP返回的状态码,范围在100-599之间

            statusText(String): 服务器返回的状态文字描述

            headers: HTTP请求返回头

            body: 返回体,这里有处理返回体的一些方法

            text(): 将返回体处理成字符串类型

           json(): 返回结果和 JSON.parse(responseText)一样

           blob(): 返回一个Blob,Blob对象是一个不可更改的类文件的二进制数据

    如果请求一个XML格式文件,则调用response.text。如果请求图片,使用response.blob方法

    注意:

      cookie传递必须在header参数里面加上credentials: 'include',才会如xhr一样将当前cookies带到请求中去

     四、get、post请求方式

      1、get

    复制代码
    var result = fetch('url', {
            credentials: 'include',
            headers: {
                'Accept': 'application/json, text/plain, */*',
            },    
     });
    复制代码

      2、post

    复制代码
    var result = fetch('/api/post', {
            method: 'POST',
            credentials: 'include',
            headers: {
                'Accept': 'application/json, text/plain, */*',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            // 注意 post 时候参数的形式
            body: "a=100&b=200"
        });
    复制代码

    五、封装get和post方法

      1、get

    复制代码
    import 'es6-promise'
    import 'whatwg-fetch'
    
    export default (url)=>({
        var result = fetch(url, {
            credentials: 'include',
            headers: {
                'Accept': 'application/json, text/plain, */*',
            },    
       })
       .then(res=>res.json());
       
       return result
    })
    复制代码

      2、post

    复制代码
    import 'es6-promise'
    import 'whatwg-fetch'
    import qs from 'qs';
    export default (url,data)=>({
        var result = fetch(url, {
            method: 'POST',
            credentials: 'include',
            headers: {
                'Accept': 'application/json, text/plain, */*',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            // 注意 post 时候参数的形式
            body: qs(data)
        })
        .then(res=>res.json())
        
        return result;
    })
    复制代码

     六、fetch与axios的区别

    复制代码
    axios("http://xxx/xxx.json?a=123'").then((res)=>{
         console.log(res)//这里的r是响应结果
    })
    
    fetch("http://www.baidu.com").then((res)=>{
            console.log(res);//是一个综合各种方法的对象,并不是请求的数据
    })
    复制代码

    fetch返回的是一个未处理的方法集合,我们可以通过这些方法得到我们想要的数据类型。如果我们想要json格式,就执行response.json(),如果我们想要字符串就response.text()

    axios 

            1、从浏览器中创建 XMLHttpRequest

            2、从 node.js 发出 http 请求

            3、支持 Promise API

            4、拦截请求和响应

            5、转换请求和响应数据

            6、自动转换JSON数据

            7、客户端支持防止CSRF/XSRF

    fetch:

        符合关注分离,没有将输入、输出和用事件来跟踪的状态混杂在一个对象里

        更加底层,提供的API丰富(request, response)

        脱离了XHR,是ES规范里新的实现方式

    1、fetchtch只对网络请求报错,对400,500都当做成功的请求,需要封装去处理

    2、fetch默认不会带cookie,需要添加配置项

    3、fetch不支持abort,不支持超时控制,使用setTimeout及Promise.reject的实

    现的超时控制并不能阻止请求过程继续在后台运行,造成了量的浪费

    4、fetch没有办法原生监测请求的进度,而XHR可以

    1、路在何方? 路在脚下 2、何去何从? 每个人都在探索,未来的方向在何处。如果说某些方向是世人已经公认的,那么就先按照公认的去走吧(ps:站在巨人的肩膀上看世界会清晰)。 如果说方向,当今世人还不清晰准确。那么就大胆往前走吧,对与错并不重要。心中的方向更加重要。
  • 相关阅读:
    Linux五种IO模型性能分析
    并发容器之CopyOnWriteArrayList(转载)
    Web.XML配置详解
    Servlet,过滤器,监听器,拦截器的区别
    JAVA反射机制详解
    Jdk1.6 JUC源码解析(13)-LinkedBlockingQueue
    Jdk1.6 JUC源码解析(12)-ArrayBlockingQueue
    Jdk1.6 JUC源码解析(6)-locks-AbstractQueuedSynchronizer
    Jdk1.6 JUC源码解析(7)-locks-ReentrantLock
    hibernate 其中七种关联关系
  • 原文地址:https://www.cnblogs.com/yuanjili666/p/11573308.html
Copyright © 2020-2023  润新知