为了账号安全,请及时绑定邮箱和手机立即绑定

Fetch API 简单总结分析

标签:
JavaScript
Using fetch

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline,
such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to
fetch resources asynchronously across the network.
Fetch API 提供了一个访问和操纵部分http管道的接口,比如请求与响应。也提供了一个全局的
容易符合逻辑的跨网络异步请求资源fetch()方法。

Feature detection

Fetch API support can be detected by checking for the existence of Headers, Request, Response or fetch() on the Window
or Worker scope. For example, you might do this in your script:

if(self.fetch) { // run my fetch request here } else { // do something with XMLHttpRequest? }

Making fetch requests

  • A basic fetch request is really simple to set up. Have a look at the following code:
    var myImage = document.querySelector('img'); fetch('flowers.jpg') .then(function(response) { return response.blob(); }) .then(function(myBlob) { var objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; });

    Supplying request options

    The fetch() method can optionally accept a second parameter, an init object that allows you to control a number of
    different settings:

`
var myHeaders = new Headers();

var myInit = { method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default' };

fetch('flowers.jpg',myInit)
.then(function(response) {
return response.blob();
})
.then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
`

Checking that the fetch was successful

A fetch() promise will reject with a TypeError when a network error is encountered, although this usually means
permission issues or similar — a 404 does not constitute a network error, for example. An accurate check for a
successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has
a value of true. The code would look something like this:
fetch('flowers.jpg').then(function(response) { if(response.ok) { response.blob().then(function(myBlob) { var objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; }); } else { console.log('Network response was not ok.'); } }) .catch(function(error) { console.log('There has been a problem with your fetch operation: ' + error.message); });

Supplying your own request object

`var myHeaders = new Headers();

var myInit = { method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default' };

var myRequest = new Request('flowers.jpg', myInit);

fetch(myRequest)
.then(function(response) {
return response.blob();
})
.then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});`

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消