This is the 6th day of my participation in the August More Text Challenge
Fetch () is an updated version of XMLHttpRequest and is used to make HTTP requests inside JavaScript scripts
This article introduces its usage
Basic request mode
Fetch () takes a URL string as an argument, and by default makes a GET request to the parameter address, returning a Promise object
// Get JSON data from the server
fetch('https://api.xxx')
.then(response= > response.json())
.then(json= > console.log(json))
.catch(err= > console.log('Request Failed', err))
Copy the code
Fetch () receives Response as a Stream object, and Response.json () is an asynchronous operation that fetches everything and turns it into a JSON object
Promises can be rewritten with await syntax to make the semantics clearer
async function getJSON() {
let url = 'https://api.xxx';
try {
let response = await fetch(url);
return await response.json();
} catch (error) {
console.log('Request Failed', error); }}Copy the code
In the example above, the await statement must be placed in a try… Catch in order to catch errors that may occur during asynchronous operations
‘await’ is used, not ‘. Then () ‘
Response success or failure
The response.status property returns a number representing the status code of the HTTP Response (for example, 200 for a successful request)
After fetch() sends the request, there is one important note to note: Fetch () will only report an error if the network is wrong, or if there is no connection, and will consider the request a success
This means that fetch() will not fail even if the server returns a status code of 4xx or 5xx.
Only through the response. status attribute, the real status code of the HTTP Response can be obtained to determine whether the request is successful
async function fetchText() {
let response = await fetch('https://api.xxx');
if (response.status == 200) {
return await response.text();
} else {
throw new Error(response.statusText); }}Copy the code
In the preceding example, the response.status attribute must be equal to 2xx (200~299) to consider the request successful. Don’t worry about url jumps (status code 3xx) because fetch() automatically changes the jump’s status code to 200
Another method is to determine if response.ok is true
if (response.ok) {
// The request succeeded
} else {
// The request failed
}
Copy the code
Other request parameters
Fetch () takes the URL as its first argument and can also accept a second argument as a configuration object to customize the HTTP request that is made.
fetch(url, optionObj)
Copy the code
OptionObj is a configuration item object that contains all Settings for the request
Optional parameters are as follows:
{
Blob, BufferSource, FormData, URLSearchParams, or USVString object
body: JSON.stringify(data), // This must match 'content-type' // Note that requests for GET or HEAD methods cannot contain body information.
// Request cache mode. // For example: default, no-cache, reload, force-cache, only-if-cached
cache: 'no-cache'.// The requested credentials. // include: omit, same-origin, include
credentials: 'same-origin'.// Request header information
headers: {
'user-agent': 'the Mozilla / 4.0 MDN Example'.'content-type': 'application/json'
},
// Request methods such as GET, POST, PUT, DELETE, etc
method: 'POST'.// Request mode // such as CORS, no-cors, or same-origin.
mode: 'cors'./ / redirection mode / / as follow | automatic redirection, error | if redirection will automatically terminate and throw an error, manual | manual processing redirection
redirect: 'follow'.//USVString // such as no-referrer, client or a URL. By default the client
referrer: 'no-referrer',}Copy the code
Note here that some headers cannot be set with the HEADERS attribute, such as Content-Length, Cookie, Host, and so on. They are automatically generated by the browser and cannot be modified