What is Fetch?
Fetch is a request interface similar to the AJax request function, and only the browser method. On the one hand, fetch is to alleviate the messy implementation of native XMLHTTPRequest. Here is an example:
To implement Ajax requests with XHR objects:
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = function() {
console.log(xhr.response);
};
xhr.onerror = function() {
console.log("There is an error");
};
xhr.send();
Using Fetch to implement Ajax requests:
fetch(url, {
method: 'GET';
}).then(res => {
res.json();
}).then(data => {
console.log(data);
}).catch(error => {
console.log(error.msg);
})
It can be seen that Fetch is much simpler than native XHR, and the Fetch return is a Promise object. However, the Fetch request does not have a cookie by default, and the request parameters need to be set. When the server returns a 400500 error code, it will not reject. Only when the request cannot be completed due to network errors, will the Fetch be rejected.
Therefore, when a Fetch request is made, there is usually a layer of encapsulation. We can do this in the following way.
function Fetch(url, options) {
let init = {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include' //Contain Cookie
}
// Consolidation request
Object.assign(init, options);
//GET Method: query characters are attached to url behind;
if(init.method == 'GET' && options.data || init.method == 'HEAD') {
let searchStr = '';
if(options.data instanceof Object) {
for(let i in options.data) {
searchStr += ( i + '=' + options.data[i] );
}
}
url = url + '?' + searchStr;
}
return fetch(url, init).then( res => {
console.log(res);
if(res.status === 200) {
console.log(res);
return res.json();
} else {
console.log('error message' + res.msg);
}
return res.json()
})
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
})
}