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;
});`