As a new object in H5, fetch was born to replace the existence of ajax. Its main purpose is just to combine with ServiceWorkers to achieve the following optimizations:
Of course, if ServiceWorkers cooperates with the browser-side database IndexedDB, then congratulations, every browser can become a proxy server. (However, I don’t think this is a good thing. It will make the front end heavier and heavier, taking the old path of the previous c/s architecture)
1. PrefaceSince it is a new method of h5, there must be some older browsers that do not support it. For those who do not support this method
The browser needs to add an additional polyfill:
[Link]: https://github.com/fis-components/whatwg-fetch
2. Usageferch(fetch):
HTML:
fetch('/users.html') //What is returned here is a Promise object. Browsers that do not support it need to use the corresponding ployfill or transcode through babel and other transcoders before executing. then(function(response) { return response .text()}) .then(function(body) { document.body.innerHTML = body})
JSON:
fetch('/users.json') .then(function(response) { return response.json()}) .then(function(json) { console.log('parsed json', json)}) .catch(function (ex) { console.log('parsing failed', ex)})
Response metadata:
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)})
Post form:
var form = document.querySelector('form')fetch('/users', { method: 'POST', body: new FormData(form)})
Post JSON:
fetch('/users', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ //here Is the request body name of the post request: 'Hubot', login: 'hubot', })})
File upload:
var input = document.querySelector('input[type=file]')var data = new FormData()data.append('file', input.files[0]) //Get the selected file content data.append( 'user', 'hubot')fetch('/avatars', { method: 'POST', body: data})3. Precautions
(1) Differences from ajax:
1. The patch method will not throw an error when grabbing data, even a 404 or 500 error, unless it is a network error or the request process is interrupted. But of course there is a solution, here is the demonstration:
function checkStatus(response) { if (response.status >= 200 && response.status < 300) { //Determine whether the response status code is normal return response //Return the original response object normally} else { var error = new Error(response .statusText) //If it is abnormal, a response error status message will be thrown error.response = response throw error }}function parseJSON(response) { return response.json()}fetch('/users') .then(checkStatus) .then(parseJSON) .then(function(data) { console.log('request succeeded with JSON response', data) }).catch( function(error) { console.log('request failed', error) })
2. A very critical issue is that the fetch method does not send cookies, which is very fatal when it is necessary to maintain a constant connection between the client and the server, because the server needs to identify a session through cookies to maintain the session state. If you want to Sending cookies requires modifying the information:
fetch('/users', { credentials: 'same-origin' //Send cookies in the same domain})fetch('https://segmentfault.com', { credentials: 'include' //Send cookies across domains} )
The figure below is the result of cross-domain access to segment
AdditionalIf nothing else, the requested url and the response url are the same, but if an operation like redirect is performed, the response.url may be different. In XHR, the response.url after redirect may not be accurate. , need to set: response.headers['X-Request-URL'] = request.url is suitable for (Firefox < 32, Chrome < 37, Safari, or IE.)
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.