对比ajax/axios/fetch

412 阅读2分钟

1、ajax

原生ajax创建

//1.创建Ajax对象 
 var xhr=new XMLHttpRequest();
//2.连接服务器(打开和服务器的连接) 
xhr.open('GET', url, true); 
//3.发送 
xhr.send(); 
//4.接收 
xhr.onreadystatechange=function (){ 
    if(oAjax.readyState==4){ 
        if(oAjax.status==200){ 
            // 成功
            fnSucc(xhr.responseText); 
         }else{ 
             //alert('失败了'); 
             if(fnFaild){ 
                 fnFaild(); 
             }
         } 
      } 
  } 

2、axios

axios({
    method: 'post',
    url: '/user/12345',
    data: {
        firstName: 'Sue',
        lastName: 'S'
    }
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

axios本质上也是对原生xhr的封装,只不过是promise的版本,符合最新的ES规范,从其官网上可以看到以下几条特性:

  • 从node.js创建http请求
  • 支持Promise api
  • 客户端支持防止CSRF
  • 提供了一些并发请求的接口

防止CSRF的攻击实现原理:在每个请求都带一个cookie中拿到的key,根据浏览器的同源策略,假冒的网站是拿不到cookie中的key,这样后台轻松辨别出这个请求是否是用户在假冒网站上的误导输入从而采取正确的策略

3、fetch


fetch(url, {
  method: "POST",
  body: JSON.stringify(data),
  headers: {
    "Content-Type": "application/json"
  },
  credentials: "same-origin"
}).then(function(response) {
  response.status     //=> number 100–599
  response.statusText //=> String
  response.headers    //=> Headers
  response.url        //=> String

  return response.text()
}, function(error) {
  error.message //=> String
})

fetch文档链接:github.github.io/fetch/

fetch的优点:

  • 语法简洁,更加语义化
  • 基于promise实现,支持async/await
  • 更加接近底层,提供丰富的api
  • 脱离了xhr,是ES规范的新的实现方式
  • 跨域的处理 credentials: "same-origin"

fetch的缺点:

  • fetch只对网络请求报错,对400,500都当做成功的请求,需要封装去处理
  • fetch默认不会带cookie,需要添加配置项
  • fetch不支持abort,不支持超时控制,使用setTimeout及Promise.reject的实现的超时控制并不能阻止请求过程继续在后台运行,造成了流量的浪费
  • fetch没有办法原生监测请求的进度,而XHR可以

参考链接:segmentfault.com/a/119000001…