brief introduction
- The Fetch API provides a JavaScript interface for accessing and manipulating specific parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method, which provides a simple and reasonable way to obtain resources asynchronously across the network.
- MDN address
content
Promise fetch(input[, init]);
- Return value: a Promise. The Response object is returned when resolve.
- input defines the resource to get
- init is an optional configuration item object, including all settings for the request
- Parameters see Fetch()
Basic implementation
// url data as parameter and data as object
fetch(url, {
// Request body
// Note that the request for GET or HEAD methods cannot contain body information.
body: JSON.stringify(data),
// Requested cache mode
// default, no store, reload, no cache, force cache, or only if cached
cache: 'no-cache',
// Credentials credentials requested, omit, same origin, or include
// This option must be provided in order to automatically send cookie s within the current domain name
credentials: 'same-origin',
// The requested pattern, such as cors, no cors, or same origin.
// Homology strategy
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json'
}, // Requested header information
method: 'POST', // Request methods: GET, POST, PUT, DELETE, etc
// The requested pattern, such as cors, no cors, or same origin.
mode: 'cors',
// Available redirect modes
// follow, error, or manual
//follow is used by default in Chrome (the default value before Chrome 47 was manual).
redirect: 'follow',
// A USVString can be no reference, client or a URL. The default is client.
referrer: 'no-referrer',
// Refererpolicy: Specifies the value of the referer field in the HTTP header.
// It may be one of the following values: no refer, no refer when downgrade, origin, origin when cross origin, unsafe URL.
// Integrity includes the requested subresource integrity value (for example: sha256 bpfbw7ivv8q2jlit13fxdyae2tjllusrsz273h2nfse =).
})
.then(response => response.json()) // parses response to JSON
Send request with credentials
fetch('https://example.com', {
// include contains credentials that can span domains
// The same origin can only contain credentials
// omit does not contain credentials
credentials: 'include'
})
Upload JSON data
var url = 'https://example.com/profile';
var data = {username: 'example'};
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // data can be `string` or {object}!
headers: new Headers({
'Content-Type': 'application/json'
})
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
Upload file
- You can upload files through HTML elements, FormData() and fetch().
var formData = new FormData();
var fileField = document.querySelector("input[type='file']");
formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);
fetch('https://example.com/profile/avatar', {
method: 'PUT',
body: formData
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
Upload multiple files
- You can upload files through HTML elements, FormData() and fetch().
var formData = new FormData();
var photos = document.querySelector("input[type='file'][multiple]");
formData.append('title', 'My Vegas Vacation');
// formData only accepts files, blobs or strings, and cannot directly pass arrays, so it must be embedded circularly
for (let i = 0; i < photos.files.length; i++) {
formData.append('photo', photos.files[i]);
}
fetch('https://example.com/posts', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
Check whether the request is successful
- To accurately judge whether the fetch() is successful, you need to include promise resolved, and then judge whether Response.ok is true. Similar to the following code:
fetch('flowers.jpg').then(function(response) {
if(response.ok) {
return response.blob();
}
throw new Error('Network response was not ok.');
}).then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});
Custom request object
- In addition to passing the address of a resource to fetch(), you can also create a request object by using the Request() constructor, and then pass it to fetch() as a parameter
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;
});
Headers object
- var myHeaders = new Headers(init);
- init can preset your Headers through an object containing any HTTP headers
// Set Headers object
var content = "Hello World";
var myHeaders = new Headers();
myHeaders.append("Content-Type", "text/plain");
myHeaders.append("Content-Length", content.length.toString());
myHeaders.append("X-Custom-Header", "ProcessThisImmediately");
// or
myHeaders = new Headers({
"Content-Type": "text/plain",
"Content-Length": content.length.toString(),
"X-Custom-Header": "ProcessThisImmediately",
});
// Get Headers object properties
console.log(myHeaders.has("Content-Type")); // true
console.log(myHeaders.has("Set-Cookie")); // false
myHeaders.set("Content-Type", "text/html");
myHeaders.append("X-Custom-Header", "AnotherValue");
console.log(myHeaders.get("Content-Length")); // 11
console.log(myHeaders.getAll("X-Custom-Header")); // ["ProcessThisImmediately", "AnotherValue"]
myHeaders.delete("X-Custom-Header");
console.log(myHeaders.getAll("X-Custom-Header")); // [ ]
Guard properties
- The Headers object has a special guard property. This property is not exposed to the Web, but it affects what can be manipulated in the Headers object.
- none: default
- Request: the headers (Request.headers) obtained from the request are read-only
- Request no CORS: read only headers obtained from requests from different domains (request. Mode no CORS)
- Response: the headers obtained from the response (Response.headers) are read-only
- immutable: the most commonly used in service workers. All headers are read-only.
Response object
- The Response instance is returned after fetch() processes promise.
The most common response attributes used are:
* Response.status — The integer (the default value is 200) is response Status code for.
* Response.statusText — String (default is"OK"),This value is the same as HTTP The status code corresponds to the message.
* Response.ok — As shown above, this attribute is used to check response Is the status in 200 - 299(Including 200 and 299). This property returns a Boolean value (en-US).
method
- Response.blob()
- The blob() method of Response mixin uses a Response stream and reads it. It returns a promise solved with Blob.
response.blob().then(function(myBlob) {
// do something with myBlob
});
var myImage = document.querySelector('img');
var myRequest = new Request('flowers.jpg');
fetch(myRequest)
.then(function(response) {
return response.blob();
})
.then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
- Response.json()
- The json() method of Response mixin receives a Response stream and reads it. It returns a Promise. The resolve result of the Promise is to parse the text body into JSON.
response.json().then(data => {
// do something with your data
});
- Response.text()
- The text() method of Response mixin provides a "Response stream" that can be read and finishes reading it. It returns a Promise object containing USVString object (that is, text), and the code of the returned result is always UTF-8.
response.text().then(function (text) {
// do something with the text response
});
- Response.formData()
- The formData() method in the Response object reads and encapsulates the data stream carried in the Response object into an object. This method will return a Promise object, which will generate a FormData object.
- This method is mainly related to service workers
response.formData()
.then(function(formdata) {
// do something with your formdata
});
Body
- Type:
- ArrayBuffer
- ArrayBufferView (Uint8Array, etc.)
- Blob/File
- string
- URLSearchParams
- FormData
Characteristic detection
if(self.fetch) {
// run my fetch request here
} else {
// do something with XMLHttpRequest?
}
be careful
- A successful fetch() check should include not only the promise resolve d, but also the Response.ok attribute true. The HTTP 404 status is not considered a network error.
- Starting with Firefox 43, if fetch() receives a URL with a user name and password (for example http://user:password@example.com), which will throw a TypeError.
- fetch() can accept cross domain cookies; you can also use fetch() to establish cross domain sessions.
- fetch will not send cookies unless you use the credentials initialization option. (since August 25, 2017, the default credentials policy has been changed to same origin. Firefox has also been modified in version 61.0b13)