fetch小解

fetch小解

原生xhr、jquery ajax、axios、fetch对比

// 原生XHR
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText)   // 从服务器获取数据
    }
}
xhr.send()

//jquery ajax
$.ajax({
    type: 'POST',
    url: url,
    data: data,
    dataType: dataType,
    success: function() {},
    error: function() {}
})

//axios
axios({
  method:'get',
  url:url,
})
  .then(function(response) {}
  .catch(function(error)));
  
// fetch
fetch(url)
  .then(response => {
      if (response.ok) {
          return response.json();
      }
  })
  .then(data => console.log(data))
  .catch(err => console.log(err))
    

我们一眼就能看出fetch和axios很像,他们的API是基于Promise设计的,经过优化后,代码会更加优雅


  try {

    const response = await fetch(url)

    const data = await response.json()

    console.log(data);

  } catch (error) {

    console.log('请求出错', error);

  }

他是浏览器底层的api,不需要引入库就能使用。

Post请求

不过他并不完善,很多情况下需要我们再次封装。

// jquery ajax
$.post(url, {name: 'test'})
// fetch
fetch(url, {
    method: 'POST',
    body: Object.keys({name: 'test'}).map((key) => {
        return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
    }).join('&')
})


由于fetch是比较底层的API,所以需要我们手动将参数拼接成’name=test’的格式,而jquery ajax已经封装好了。所以fetch并不是开箱即用的。

另外,fetch还不支持超时控制。

带Cookie发送请求

如果我们想要在异步请求中带上cookie参数,那么需要显式指定credentials参数:

fetch(url, {
  credentials: 'include'
})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值