XMLHttpRequest, the latest alternative technology -- Fetch

Source: Internet
Author: User
In Web applications, JavaScript uses XMLHttpRequest (XHR) to execute asynchronous requests. this is a technology that effectively improves page communication. when we talk about Ajax technology, it usually means Ajax based on XMLHttpRequest. Although Ajax is useful, it is not the best API. in terms of design, it does not comply with the separation of duties principle, and the state of input, output, and event tracking is mixed into one object. Moreover, the event-based model lags behind the popular JavaScript Promise and generator-based asynchronous programming models. This article will introduce XMLHttp in Web applications. JavaScript uses XMLHttpRequest (XHR) to execute asynchronous requests. this is a technology that effectively improves page communication, when talking about Ajax technology, it usually means Ajax based on XMLHttpRequest. Although Ajax is useful, it is not the best API. in terms of design, it does not comply with the separation of duties principle, and the state of input, output, and event tracking is mixed into one object. Moreover, the event-based model lags behind the popular JavaScript Promise and generator-based asynchronous programming models. This article will introduce Fetch API, the latest alternative technology of XMLHttpRequest, which is the formal standard of W3C.

Compatibility

Before introduction, let's take a look at the currently popular browser's support for the Fetch API:

Fetch support is currently in its early stages. it is supported in Firefox 39 and Chrome 42 and above.


If you want to use it now, you can also use Fetch Polyfil to support browsers that do not yet support Fetch.


Before using Fetch, you can also perform functional testing on it:

if(self.fetch) {    // run my fetch request here} else {    // do something with XMLHttpRequest?}

Simple fetching example


In the Fetch API, the most common function is the fetch () function. It receives a URL parameter and returns a promise to process response. Response is a Response object:

fetch("/data.json").then(function(res) {  // res instanceof Response == true.  if (res.ok) {    res.json().then(function(data) {      console.log(data.entries);    });  } else {    console.log("Looks like the response wasn't perfect, got status", res.status);  }}, function(e) {  console.log("Fetch failed!", e);});


Fetch () accepts the Second Optional parameter, an init object that can control different configurations. If a POST request is submitted, the code is as follows:

Fetch ("http://www.example.org/submit.php", {method: "POST", headers: {"Content-Type": "application/x-www-form-urlencoded"}, body: "firstName = Nikhil & favColor = blue & password = easytoguess "}). then (function (res) {if (res. OK) {// res. OK is used to check whether the request is successful. log ("Perfect! Your settings are saved. ");} else if (res. status = 401) {console. log (" Oops! You are not authorized. ") ;}}, function (e) {console. log (" Error submitting form! ");});

In case of a network failure, fetch () promise will reject with a TypeError object. To accurately determine whether fetch () is successful, you need to include promise resolved, and then judge whether Response. OK is true.


Fetch implements four interfaces: GlobalFetch, Headers, Request, and Response. GloabaFetch contains only one fetch method for obtaining network resources, and the other three directly correspond to the corresponding HTTP concepts. Body is also obfuscated in request/reponse.

Headers

The Headers interface allows you to define the HTTP Request header (Request. headers) and Response header (Response. headers ). A Headers object is a simple multi-name value pair:

var content = "Hello World";var myHeaders = new Headers();myHeaders.append("Content-Type", "text/plain");myHeaders.append("Content-Length", content.length.toString());myHeaders.append("X-Custom-Header", "ProcessThisImmediately");


You can also upload a multi-dimensional array or object literal volume:

myHeaders = new Headers({  "Content-Type": "text/plain",  "Content-Length": content.length.toString(),  "X-Custom-Header": "ProcessThisImmediately",});

In addition, the Headers interface provides APIs such as set and delete to retrieve the content:

console.log(reqHeaders.has("Content-Type")); // trueconsole.log(reqHeaders.has("Set-Cookie")); // falsereqHeaders.set("Content-Type", "text/html");reqHeaders.append("X-Custom-Header", "AnotherValue");console.log(reqHeaders.get("Content-Length")); // 11console.log(reqHeaders.getAll("X-Custom-Header")); // ["ProcessThisImmediately", "AnotherValue"]reqHeaders.delete("X-Custom-Header");console.log(reqHeaders.getAll("X-Custom-Header")); // []


Although some operations are only used in ServiceWorkers, compared with XHR, it provides very convenient Headers APIs.


For security reasons, some header fields can only be set through the User Agent, but cannot be set through programming: request header forbidden fields and response header forbidden fields.


If an invalid HTTP Header attribute name is used or a non-writable attribute is written, the Headers method usually throws a TypeError exception:

var myResponse = Response.error();try {  myResponse.headers.set("Origin", "http://mybank.com");} catch(e) {  console.log("Cannot pretend to be a bank!");}

The best practice is to check whether the content type is correct before use, for example:

fetch(myRequest).then(function(response) {  if(response.headers.get("content-type") === "application/json") {    return response.json().then(function(json) {      // process your JSON further    });  } else {    console.log("Oops, we haven't got JSON!");  }});

Because Headers can be sent in a request or received in a response request, and specify which parameters are writable, the Headers object has a special guard attribute. This property is not exposed to the Web, but it affects which content can be changed in the Headers object.


Possible values:


None: The default

R

Equest: headers (request. headers) read-only request-no-cors: requests from different domains. headers read-only response obtained in the request of mode no-cors: headers (response. headers) read-only immutable: The most commonly used in ServiceWorkers. all headers are read-only.


Request


The Request interface defines the request format of resources requested through HTTP. a simple Request is constructed as follows:

Var req = new Request ("/index.html"); console. log (req. method); // "GET" console. log (req. url); // The http://example.com/index.html console. log (req. headers); // request header

Like fetch (), Request accepts the Second Optional parameter, an init object that can control different configurations:

var myHeaders = new Headers();var myInit = { method: 'GET',               headers: myHeaders,               mode: 'cors',               cache: 'default' ,               credentials: true,               body: "image data"};var myRequest = new Request('flowers.jpg',myInit);fetch(myRequest,myInit).then(function(response) {  return response.blob();}).then(function(myBlob) {  var objectURL = URL.createObjectURL(myBlob);  myImage.src = objectURL;});


The mode attribute is used to determine whether cross-origin requests are allowed and which response attributes are readable. Optional mode attribute values:

Same-origin: requests follow the same origin policy

No-cors: default value. it allows scripts from CDN, images from other domains, and other cross-origin resources (the precondition is that the method can only be HEAD, GET, or POST)

Cors: Cross-origin is allowed. requests follow the CROS protocol.

The credentials enumeration attribute determines whether cookies can be obtained across domains. this is the same as the withCredentials flag of XHR, but there are only three values: omit (default), same-origin, and include.

Response

The Response instance is returned after fentch () processes promises. Its instance can also be created using JavaScript, but it is only useful in ServiceWorkers. When the respondWith () method is used and a custom response is provided to accept the request:

 var myBody = new Blob();addEventListener('fetch', function(event) {  event.respondWith(new Response(myBody, {    headers: { "Content-Type" : "text/plain" }  });});


The Response () constructor accepts the data body of two optional parameters-response and an initialization object (similar to the init parameter accepted By Request .)

The most common response attributes are:

Response. status-integer (200 by default) is the status code of response. response. statusText-string (default value: OK), which corresponds to the HTTP status code message. response. OK-as shown above, this attribute is used to check whether the response status is in the range of 200-299 (including 200,299. this attribute returns a Boolean value. response. headers-Response header Response. type-response type, such as basic/cors/error

Body

Both Request and Response implement the Body interface. during the Request process, both of them carry the Body, which can be any of the following types of instances:

ArrayBufferArrayBufferViewBlob/fileURLSearchParamsFormData

In addition, both Request and Response provide the following methods for their bodies, all of which return a Promise object:

arrayBuffer()blob()json()text()formData()


The above is the content of Fetch, the latest alternative technology for XML Http requests. For more information, see PHP Chinese website (www.php1.cn )!

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.