Fetch
Reference: developers.google.com/web/updates…
There are probably some very old programs that still use XHR, written as follows:
const request = new XMLHttpRequest()
request.responseType = 'json'
request.open('GET'.'/url'.true)
request.onload = (a)= > {
console.log(request.response)
}
request.onerror = (a)= > {
console.log('shits happen! ')
}
request.send(null)
Copy the code
This way using XHR for asynchronous access and reading resources can be cumbersome. Fetch() allows you to create xHR-like network access, but with a simpler and cleaner API that doesn’t require multiple callbacks and remembers XHR’s complex API. The Fetch API is based on Promises.
XMLHttpRequest
A relatively complete XMLHttpRequest listens for at least two events (onLoad, onError) to implement successful and failed callbacks, as well as calls to open() and send()
function reqListener() {
var data = JSON.parse(this.responseText);
console.log(data);
}
function reqError(err) {
console.log('Fetch Error :-S', err);
}
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.onerror = reqError;
oReq.open('get'.'./api/some.json'.true);
oReq.send();
Copy the code
Fetch
A simple Fetch example is as follows:
fetch('./api/some.json')
.then(
function(response) {
if(response.status ! = =200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
Copy the code
Fetch’s syntax is more semantic and easier to understand. In the above example, we first determine the status code of response. If it is 200, we parse the response into JSON
Fetch () returns a Stream in response, so when we call Response. json, we return a Promise because we read the Stream asynchronously.
Fetch optimizes code with Async
Since the underlying Fetch is implemented with Promise, we can directly use Async to optimize the above code, reduce callbacks, and make it more semantic and easy to understand
async function geturl(){
try{
let res = await fetch('./api/some.json')
if(res.status == 200) {console.log(await res.text())
}
} catch(err){
console.log(err)
}
}
Copy the code
The Response of metadata
In the above example, we learned about the status of the Response object and how to convert the Response object into a JSON object. Let’s look at the other metadata of the Response object:
fetch('users.json').then(function(response) {
console.log(response.headers.get('Content-Type'));
console.log(response.headers.get('Date'));
console.log(response.status);
console.log(response.statusText);
console.log(response.type);
console.log(response.url);
});
Copy the code
The Response type
When we send a Fetch request, the response response will come with a Response. type attribute (basic, CORS, opaque). The Response. type attribute indicates the source of the asynchronous resource and how it should be handled.
When we make a same-origin request, response.type is basic, and you can read all the information from response.
If we access a non-cognate domain name and have the corresponding CORs response header returned, the request type is CORs. Cors is very similar to Basic, except that you can’t access cache-Control, Content-Language, Content-Type, Expires, Last-Modified, and Pragma in cORS responses
When a request is made to the domain name of a different source, if the response header does not contain CORS information, the response type is Opaque. An Opaque response cannot read the returned data, state, or even determine whether the request was successful.
We can customize the Fetch request mode to return the corresponding type of response, including the following:
- Same-origin only returns same-origin requests. All other types are rejected
- Cors receives cognate and non-cognate requests and returns a response with a CORS header
- Cers-with-formed-preflight performs a security check before issuing a request
- No-cors Initiates a non-same-origin request without the CORS header, and opaque response is returned. However, this type can only be used in Service workers, not in window.fetch
fetch('http://some-site.com/cors-enabled/some.json', {mode: 'cors'})
.then(function(response) {
return response.text();
})
.then(function(text) {
console.log('Request successful', text);
})
.catch(function(error) {
log('Request failed', error)
});
Copy the code
Commitment to the chain
Since the response returned by the Fetch is based on the Promise implementation, we can chain several promises together like this:
function status(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}
function json(response) {
return response.json()
}
fetch('users.json')
.then(status)
.then(json)
.then(function(data) {
console.log('Request succeeded with JSON response', data);
}).catch(function(error) {
console.log('Request failed', error);
});
Copy the code
Of course, we can also use Async for code optimization
async function geturl(url){
try {
let res = await fetch(url)
if(res.status >= 200 && res.status < 300) {console.log('Request succeeded with JSON response'.await res.json())
}
}catch (err){
console.log(err)
}
}
geturl('users.json')
Copy the code
A Post request
When we use Fetch to initiate a Post request, we need to manually set the method and body parameters as follows:
fetch(url, {
method: 'post'.headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: 'foo=bar&lorem=ipsum'
})
.then(json)
.then(function (data) {
console.log('Request succeeded with JSON response', data);
})
.catch(function (error) {
console.log('Request failed', error);
});
Copy the code
If method is not explicitly specified, the default Get request is
Send a request with a Cookie
If we want to take the cookie argument with the asynchronous request, we need to specify the credentials argument explicitly:
fetch(url, {
credentials: 'include'
})
Copy the code