Fetch -- http请求的另一种姿势

发布时间:2019-08-10 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Fetch -- http请求的另一种姿势脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

传统Ajax是利用XMLHttPRequest(Xhr)发送请求获取数据,不注重分离的原则。而Fetch API是基于Promise设计,专为解决XHR问题而出现。

原文链接

简介

XMLHttpRequest是一个设计粗糙的API,其中配置和调用方式非常混乱。
使用XHR发送一个json请求:

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做请求后:

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兼容性

浏览器兼容性

Fetch -- http请求的另一种姿势

Fetch -- http请求的另一种姿势

fetch原生支持性不高,不过可以使用一些polyfill。

fetch常见问题

  • fetch请求默认不带cookie,需要设置fetch(url,{credentials: 'include'});
  • 服务器返回400、500错误码不会reject,只有网路错误请求不能完成时才会reject;

总结

fetch API看起来简单,却是js语法不断增强提高带来的改善。
由于项目中普遍会引入各种库去解决底层问题,对于基础api的新增、拓展不太关注,久而久之会产生一种与标准的脱离感。以后应多多关注底层api的变化与基础实现。

脚本宝典总结

以上是脚本宝典为你收集整理的Fetch -- http请求的另一种姿势全部内容,希望文章能够帮你解决Fetch -- http请求的另一种姿势所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。