Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Fetch, the latest substitute Technology for HttpRequest in XML

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is about how to use Fetch, the latest alternative to HttpRequest in XML. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

In Web applications, JavaScript executes asynchronous requests through XMLHttpRequest (XHR), which is an effective technology to improve page communication. When we talk about Ajax technology, it usually means Ajax based on XMLHttpRequest. While Ajax is useful, it is not the best API, and it is not designed to conform to the principle of separation of responsibilities, mixing input, output, and state tracked by events into one object. Moreover, the event-based model runs counter to Promise, which is popular in JavaScript, and the generator-based asynchronous programming model. The content of this article is the latest alternative technology of XMLHttpRequest-Fetch API, which is the official standard of W3C.

Compatibility

Before introducing this, let's take a look at the current support for Fetch API in mainstream browsers:

Support for Fetch is still in its early stages, with support above Firefox 39 and above Chrome 42.

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 tests on it:

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

A simple example of fetching

In Fetch API, the most common function is the fetch () function. It takes a URL parameter and returns a promise to process the 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 a 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 detect whether the request was successful or not console.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! ");})

If you encounter a network failure, fetch () promise will reject with a TypeError object. To accurately determine whether fetch () is successful, you need to include the case of promise resolved, and then determine 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. In addition, Body is confused in request/reponse.

Headers

The Headers interface allows you to define the request header (Request.headers) and response header (Response.headers) of the HTTP. 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 pass a multidimensional array or the literal amount of an object:

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

In addition, the Headers interface provides API such as set and delete to retrieve its contents:

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, they themselves provide a very convenient API for manipulating Headers compared to XHR.

For security reasons, some header fields can only be set through User Agent, not programmatically: request header disabled fields and response header disabled fields.

If you use an illegal HTTP Header property name or write an unwritable property, Headers's methods usually throw 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 that the content type is correct before using it, such as:

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 request or received in a response request, and specifies which parameters are writable, the Headers object has a special guard property. This property is not exposed to Web, but it affects what can be changed in the Headers object.

Possible values are as follows:

None: default

R

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

Request

The Request API defines the request format for requesting resources through HTTP. A simple request is constructed as follows:

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

Like fetch (), Request accepts a 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-domain requests are allowed and which response attributes are readable. Optional attribute values for mode:

Same-origin: request follows the same origin policy

No-cors: default value, which allows scripts from CDN, pictures from other domains, and other cross-domain resources (provided that method can only be HEAD,GET or POST)

Cors: cross-domain is allowed. Requests follow CROS protocol.

The credentials enumeration property determines whether cookies can be obtained across domains, which is the same as the withCredentials flag of XHR, but has only three values, namely omit (default), same-origin, and include.

Response

The Response instance is returned after fentch () has finished processing the promises, and its instance can also be created through JavaScript, but it is only really useful in ServiceWorkers. When you use the respondWith () method and provide a custom response to accept request:

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

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

The most common response properties are:

Response.status-Integer (default is 20000) is the status code of response. Response.statusText-string (default is OK), this value corresponds to HTTP status code message .Response.ok-as shown above, this property is used to check whether the status of response is in the range of 200299 (including 200299). This property 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 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 body, which both return a Promise object:

ArrayBuffer () blob () json () text () formData () Thank you for reading! This is the end of the article on "how to use Fetch, the latest alternative technology for HttpRequest in XML". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report