Fetch

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, reasonable way to fetch resources asynchronously across a network.

A concept,

Fetch provides a generic definition of the Request and Response objects. In the future, it can be used in more scenarios: whether it’s service workers, Cache apis, or other ways of handling requests and responses, or even anything that requires you to generate your own responses in your application.

It also provides a new definition for related concepts, such as CORS and HTTP native headers, instead of their separate definitions.

Second, the grammar

Promise<Response> fetch(input[, init]);
Copy the code
1, parameters,
input

Define the resource to capture. This could be:

  • aUSVStringA string containing the resource to be obtainedURL. Some browsers will accept itblob:data:As aschemes.
  • aRequestObject.
Init optional

A configuration item object that contains all Settings for the request. The optional parameters are:

  • method: Request method used, such asGET,POST.
  • headers: Specifies the request header in the form ofHeadersObject or containing
  • ByteStringValue is an object literal.

Body: The requested body information: could be a Blob, BufferSource, FormData, URLSearchParams, or USVString object. Note that requests for the GET or HEAD methods cannot contain body information.

  • mode: Request mode, such ascors,no-corsorsame-origin.
  • credentials: the requestcredentials, such asomit,same-originorinclude.This option must be provided in order to automatically send cookies within the current domain name, is also acceptableFederatedCredentialAn instance or an examplePasswordCredentialInstance.
  • cache: the requestcacheMode:defaultno-storereloadno-cacheforce-cacheoronly-if-cached.
  • redirect: availableredirectMode:follow(Automatic redirection),error(A redirection will terminate automatically and an error will be thrown), ormanual(Handle redirection manually). The default value ismanual.
  • referrerA:USVStringCan beno-referrer,clientOr aURL. The default isclient.
  • referrerPolicy: specifies theHTTPThe headrefererField value. May be one of the following values:no-referrer,no-referrer-when-downgrade,origin,origin-when-cross-origin,unsafe-url
  • integrity: including requestedsubresource integrityValue (for example: sha256 – BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE =).
2. Return value

A Promise, resolve returns a Response object.

The difference between Fetch and Ajax

  1. When an error is receivedHTTPStatus code when fromfetch()The returnedPromiseWill not be marked asreject, even if the responseHTTPThe status code is 404 or 500. Instead, it willPromiseThe status is marked asresolve (But willresolveOf the return value ofokProperty set tofalse) is flagged only when the network fails or the request is blockedreject.
  2. fetch()Cross-domain is acceptablecookies; You can also set up a cross-domain session using fetch().
  3. fetchWill not send by defaultcookies. Unless you use itcredentialsThe initialization option of. The credentials value is same-origin.

Request example

The sample
fetch('https://api.github.com/users/chriscoyier/repos').then(res= > {
	console.log(res)
}).catch((e) = > {
	console.log(e)
})
Copy the code
Printed logs
body: ReadableStream
bodyUsed: true
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "https://api.github.com/users/chriscoyier/repos"
__proto__: Response
Copy the code
Transformation (Body mixin)
attribute

Body. Body a simple getter for exposing the Body content of a ReadableStream type. Body.bodyUsed A Boolean value indicating whether the Body has been read by the tag.

methods

Body.arraybuffer () causes Response to suspend a stream operation and read its value upon completion, which returns a Promise object whose resolve parameter is of type arrayBuffer. This action changes the bodyUsed state to used (true).

Body.blob() causes Response to suspend a stream operation and read its value upon completion, which returns a Promise object whose resolve parameter is of type BLOb. This action changes the bodyUsed state to used (true).

Body.formdata () causes Response to suspend a stream operation and read its value when completed, which returns a Promise object whose resolve parameter is of type formData form. This action changes the bodyUsed state to used (true).

Body.json() causes Response to suspend a stream operation and read its value when completed, which returns a Promise object whose resolve parameter type is the result of parsing the Body text using JSON. This action changes the bodyUsed state to used (true).

Body.text() causes Response to suspend a stream operation and read its value upon completion, which returns a Promise object whose resolve argument is of type USVString (text). This action changes the bodyUsed state to used (true).

Complete sample

fetch('https://api.github.com/users/chriscoyier/repos').then(res= > {
	console.log('res', res)
	console.log('res.body', res.body)
	console.log('res.bodyUsed', res.bodyUsed)
	res.json().then(_res= > {
		console.log('res.bodyUsed', res.bodyUsed)
		console.log('_res', _res)
	}).catch(e= > {
		console.log(e)
	})
}).catch((e) = > {
	console.log(e)
})
Copy the code

Print log

'res' 
	body: (...).bodyUsed: true
	headers: Headers {}
	ok: true
	redirected: false
	status: 200
	statusText: "OK"
	type: "cors"
	url: "https://api.github.com/users/chriscoyier/repos"

'res.body' ReadableStream {locked: false}

'res.bodyUsed' false

'res.bodyUsed' true

//res.json() parsed value
'_res' (30) [{...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}. {...}, {...}, {...}, {...}, {...}]Copy the code
async/await
(async() = > {let res = await fetch('https://api.github.com/users/chriscoyier/repos')
	console.log(res)
})();
Copy the code
The sample
1. Carry cookies

credentials

To get the browser to send a request containing credentials (even if it is a cross-domain source), add the Credentials: ‘include’ to the init object passed to the fetch() method.

fetch(url, {
  	credentials: 'include'  
})
Copy the code

Add credentials: ‘same-origin’ if you only want to send credentials when the request URL is in the same origin as the calling script. To ensure that the browser does not include credentials in the request instead, use credentials: ‘omit’.

fetch(url, {
  	credentials: 'same-origin' //credentials: 'omit' 
})
Copy the code
2. Upload JSON data

‘Content-Type’: ‘application/json’

let url = 'https://xxx';
let data = { username: 'example' };

fetch(url, {
    method: 'POST'.body: JSON.stringify(data),
    headers: new Headers({
        'Content-Type': 'application/json'
    })
}).then(res= > res.json())
.catch(error= > console.error('Error:', error));
Copy the code
3. Upload files

FormData()

let formData = new FormData();
let fileField = document.querySelector("input[type='file']");

formData.append('name'.'abc123');
formData.append('pic', fileField.files[0]);

fetch(url, {
    method: 'PUT'.body: formData
})
.then(response= > response.json())
.catch(error= > console.error('Error:', error));
Copy the code
4. Upload multiple files

<input type=”file” mutiple/>

let formData = new FormData();
let photos = document.querySelector("input[type='file'][multiple]");

formData.append('title'.'My Vegas Vacation');
// formData only accepts files, blobs, or strings. It cannot pass arrays directly, so it must be inserted in a loop
for (let i = 0; i < photos.files.length; i++) {
    formData.append('photo', photos.files[i]);
}

fetch(url, {
    method: 'POST'.body: formData
})
.then(response= > response.json())
.then(response= > console.log('Success:'.JSON.stringify(response)));
Copy the code
5. Customize the 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 passing it to fetch() as an argument:

let myHeaders = new Headers();

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

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

fetch(myRequest).then((response) = > {
}).then((myBlob) = > {});
Copy the code

Request() and fetch() accept the same arguments. You can even pass in an existing Request object to create a copy:

var anotherRequest = new Request(myRequest,myInit);
Copy the code

Five, the Headers

You can create your own Headers object using the Headers() constructor. A HEADERS object is a simple multi-name value pair.

let content = "Hello World";
let myHeaders = new Headers();
myHeaders.append("Content-Type"."text/plain");
myHeaders.append("Content-Length", content.length.toString());
myHeaders.append("X-Custom-Header"."ProcessThisImmediately");
Copy the code

You can also pass a multidimensional array or object literal:

myHeaders = new Headers({
  	"Content-Type": "text/plain"."Content-Length": content.length.toString(),
  	"X-Custom-Header": "ProcessThisImmediately"});Copy the code
Guard properties

Since Headers can be sent in a Request or received in a response request, and specifies which parameters are writable, 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: the default
  • request: The headers obtained from request (request.headers) is read-only
  • request-no-cors: Headers obtained from requests of different fields (request. mode no-cors) are read-only
  • responseHeaders obtained from Response (response.headers) is read-only
  • immutable: Most commonly used in ServiceWorkers, all headers are read-only.

6. Response object

The Response instance is returned after fetch() has processed the promise.

attribute
  • Response.headersread-only

Contains the Headers object associated with this Response.

  • Response.okread-only

Contains a Boolean value indicating that the Response was successful (the HTTP status code ranges from 200 to 299).

  • Response.redirectedread-only

Indicates whether the Response came from a redirect, and if so, its URL list will have multiple entries.

  • Response.statusread-only

A status code containing Response (for example, 200 for success).

  • Response.statusTextread-only

Contains status information consistent with the Response status code (for example, OK corresponds to 200).

  • Response.typeread-only

The type that contains Response (for example, BASIC, CORS).

  • Response.urlread-only

The URL that contains Response.

  • Response.useFinalURL

Contains a Boolean to indicate whether this is the final URL for the Response. Response implements the Body interface, so the following attributes are also available:

  • Body.bodyread-only

A simple getter for exposing the body content of a ReadableStream type.

  • Body.bodyUsedread-only

Contains a Boolean value to indicate whether the Response has read the Body.

methods
  • Response.clone()

Create a clone of the Response object.

  • Response.error()

Returns a new Response object bound to a network error.

  • Response.redirect()

Create a new Response with another URL. Response implements the Body interface, so all Body methods can be used