Explanation of the fetch method in h5 (Summary), h5fetch

Source: Internet
Author: User
Tags send cookies hubot

Explanation of the fetch method in h5 (Summary), h5fetch

Fetch Concept

As a new object in H5, fetch was born to replace the existence of ajax. The main purpose is only to combine ServiceWorkers to achieve the following optimization:

  1. Optimize offline experience
  2. Scalability

Of course, if ServiceWorkers works with the browser-side database IndexedDB, congratulations! Every browser can become a proxy server. (However, I don't think this is a good thing. This will make the front-end more and more important and take the old path of the c/s architecture)

1. Preface

Since it is a new h5 method, some older browsers certainly do not support it, for those that do not support this method

The browser needs to add an additional polyfill:

[LINK]: https://github.com/fis-components/whatwg-fetch

2. Usage

Ferch (capture ):

HTML:

Fetch ('/users.html') // a Promise object is returned here. browsers that are not supported need the corresponding ployfill or transcode through the transcoding tool such as babel. 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: {'access': 'application/json', 'content-type': 'application/json '}, body: JSON. stringify ({// here is the name of the post Request body: 'hubot ', login: 'hubot ',})})

File upload:

Var input = document. querySelector ('input [type = "file"] ') var data = new FormData () data. append ('file', input. files [0]) // obtain the selected file content data. append ('user', 'hubot ') fetch ('/avatars ', {method: 'post', body: data })

3. Notes

(1) differences with ajax:

1. The fatch method will not throw an error even if it is a 404 or 500 error, unless it is a network error or the request is interrupted. But of course there is a solution. The following is demonstration:

Function checkStatus (response) {if (response. status> = 200 & response. status <300) {// determine whether the response status code is normal return response // returns the original response object normally} else {var error = new Error (response. statusText) // if it is abnormal, an error is returned. 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 key issue is that the fetch method does not send cookies, which is critical for maintaining frequent connections between the client and the server, because the server needs to use cookies to identify a session to maintain the session state. to send a cookie, modify the following information:

Fetch ('/users', {credentials: 'same-origin' // send cookie in the same domain}) fetch ('https: // segmentfault.com', {credentials: 'include '// send cookie across domains })

Is the result of cross-origin access segment.

Additional

If there is no accident, the request url is the same as the response url, but if the operation is like redirect, the response will be returned. the url may be different. in XHR, the response after redirect. the url may not be accurate. You need to set it as response. headers ['x-Request-url'] = request. url applies to (Firefox <32, Chrome <37, Safari, or IE .)

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.