• fetch与xhr的对比


    ㈠fetch的简单介绍

    fetch是一种HTTP数据请求的方式,是XMLHttpRequest的一种替代方案。

    fetch不是ajax的进一步封装,而是原生js。

    Fetch函数就是原生js,没有使用XMLHttpRequest对象。

    ㈡XMLHttpRequest   API  的缺点

    ⑴ 不符合关注分离(Separation of Concerns)的原则

    ⑵ 配置和调用方式非常混乱

    ⑶ 基于事件的异步模型写起来也没有现代的 Promise,generator/yield,async/await 友好。

    ⑷具体示例:

    var xhr = new XMLHttpRequest();
    
    xhr.open('GET',url);
    
    xhr.responseType = 'json';
    
    xhr.onload = function(){
       
       console.log(xhr.response);
    }
    
    xhr.onerror = function(){
       
       console.log('xhr error');
    }
    
    xhr.send();

    ㈢Fetch 的出现就是为了解决 XHR 的问题

    ⑴使用fetch做请求后:

    fetch(url).then(function(response){
         
          return response.json();
    
    }).then(function(data){
        
          console.log(data);
    
    }).catch(function(e){
        
          console.log('error' + e);
    });

    ⑵es6写法:

    fetch(url).then(response=>response.json())
        
        .then(data=>console.log(data))
        
        .catch(e=>console.log('error' + e));

    ⑶处理text/html响应:

    fetch(url).then(response=>response.text())
        
         .then(data=>console.log(data))
        
         .catch(e=>console.log('error' + e));

    ⑷获取头信息:

    fetch(url).then((response)=>{
        
        console.log(response.status);
        
        console.log(response.statusText);
        
        console.log(response.headers.get('Content-Type'));
        
        console.log(response.headers.get('Date'));
       
        return response.json();
    
    }).then(data=>console.log(data))
      
        .catch(e=>console.log('error' + e);

    ⑸设置头信息

    fetch(url,{
       
       headers:{
            
                 'Accept': 'application/json',
          
                 'Content-Type': 'application/json'
        }
    
    }).then(response=>response.json())
      
        .then(data=>console.log(data))
      
         .catch(e=>console.log('error' + e);

    ⑹提交表单

    fetch(url,{
        
         method: 'post',
        
         body: new FormData(document.getElementById('form'))
    
    }).then(response=>response.json())
        
        .then(data=>console.log(data))
      
        .catch(e=>console.log('error' + e);

    ⑺提交json数据

    fetch(url,{
        
        method: 'post',
        
        body: JSON.stringify({
            
              username: document.getElementById('username').value,
            
              password: document.getElementById('password').value
        })
    
    }).then(response=>response.json())
      
        .then(data=>console.log(data))
      
        .catch(e=>console.log('error' + e);

    ⑻fetch跨域的处理

    fetch中可以设置mode为"no-cors"(不跨域)

    fetch('/users.json', {
        method: 'post',
        mode: 'no-cors',
        data: {}
    }).then(function() { /* handle response */ });

    这样之后我们会得到一个type为“opaque”的返回。

    需要指出的是,这个请求是真正抵达过后台的,

    所以我们可以使用这种方法来进行信息上报,在我们之前的image.src方法中多出了一种选择,

    另外,我们在network中可以看到这个请求后台设置跨域头之后的实际返回,有助于我们提前调试接口(当然,通过chrome插件我们也可以做的到)。

    ㈣Fetch 优点

    ⑴语法简洁,更加语义化

    ⑵基于标准 Promise 实现,支持 async/await

    ⑶同构方便,使用 isomorphic-fetch

    ㈤Fetch 的兼容问题:

    ⒈fetch原生支持性不高,引入下面这些 polyfill 后可以完美支持 IE8+ :

    ⑴由于 IE8 是 ES3,需要引入 ES5 的 polyfill: es5-shim, es5-sham

    ⑵引入 Promise[z1]  的 polyfill: es6-promise

    ⑶引入 fetch 探测库:fetch-detector

    ⑷引入 fetch 的 polyfill: fetch-ie8

    ⑸可选:如果你还使用了 jsonp,引入 fetch-jsonp

    ⑹可选:开启 Babel 的 runtime 模式,现在就使用 async/await

    ⒉示例:

    使用isomorphic-fetch,兼容Node.js和浏览器两种环境运行。

    npm install --save isomorphic-fetch es6-promise
    
    require('es6-promise').polyfill();
    
    require('isomorphic-fetch');

    参考:https://blog.csdn.net/kezanxie3494/article/details/102956869

  • 相关阅读:
    20191224 Spring官方文档(Overview)
    20191224 Spring官方文档(启动)
    20191209 【归档】Linux就该这么学
    20191209 Linux就该这么学(6)
    20191209 Linux就该这么学(5)
    20191209 Linux就该这么学(4)
    20191209 Linux就该这么学(1-3)
    20191128 Spring Boot官方文档学习【目录】
    加密在卷积神经网络上的应用
    Federated Optimization: Distributed Machine Learning for On-Device Intelligence
  • 原文地址:https://www.cnblogs.com/shihaiying/p/12114721.html
Copyright © 2020-2023  润新知