zoukankan      html  css  js  c++  java
  • 【巷子】---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可以

     

  • 相关阅读:
    Linux下sed,awk,grep,cut,find学习笔记
    Python文件处理(1)
    KMP详解
    Java引用详解
    解决安卓中页脚被输入法顶起的问题
    解决swfupload上传控件文件名中文乱码问题 三种方法 flash及最新版本11.8.800.168
    null id in entry (don't flush the Session after an exception occurs)
    HQL中的Like查询需要注意的地方
    spring mvc controller间跳转 重定向 传参
    node to traverse cannot be null!
  • 原文地址:https://www.cnblogs.com/nanianqiming/p/10029938.html
Copyright © 2011-2022 走看看