首页 > web前端 > js教程 > 正文

用Fetch进行http请求

php中世界最好的语言
发布: 2018-03-13 16:01:17
原创
3235人浏览过

这次给大家带来用fetch进行http请求,用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特点

语法简洁,更加语义化

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

同构方便,使用isomorphic-fetch

fetch兼容性

浏览器兼容性

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

IE8是es3语法,需要引入es5的polyfill:es5-shim

支持promise语法:es6-promise

fetch的polyfill:fetch-polyfill

使用jsonp还需要引入:fetch-jsonp

开启babel的runtime模式,可以使用async/await

fetch常见问题

fetch请求默认不带cookie,需要设置fetch(url,{credentials: 'include'});

服务器返回400、500错误码不会reject,只有网路错误请求不能完成时才会reject;

总结

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

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

React.js中的CSS使用

JS中的async/await

以上就是用Fetch进行http请求的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号