Jquery Fetch Api

Posted on  by admin

JS HTML DOM

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses.

  • Guard

    • It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.
      This kind of functionality was previously achieved using XMLHttpRequest.
    • Fetch provides a better alternative that can be easily used by other technologies such as Service Workers.
      Fetch also provides a single logical place to define other HTTP-related concepts such as CORS and extensions to HTTP.
    • The fetch specification differs from jQuery.ajax() in the following significant ways:.
      The Promise returned from fetch()won't reject on HTTP error status even if the response is an HTTP 404 or 500.

Instead, as soon as the server responds with headers, the Promise will resolve normally (with the ok property of the response set to false if the response isn't in the range 200–299), and it will only reject on network failure or if anything prevented the request from completing.

Unless fetch() is called with the credentials option set to include, fetch(): won't send cookies in cross-origin requestswon’t set any cookies sent back in cross-origin responses. won't send cookies in cross-origin requests.

won’t set any cookies sent back in cross-origin responses.

A basic fetch request is really simple to set up.
Have a look at the following code:.
Here we are fetching a JSON file across the network and printing it to the console.
The simplest use of fetch() takes one argument — the path to the resource you want to fetch — and does not directly return the JSON response body but instead returns a promise that resolves with a Response object.
The Response object, in turn, does not directly contain the actual JSON response body but is instead a representation of the entire HTTP response.

So, to extract the JSON body content from the Response object, we use the json() method, which returns a second promise that resolves with the result of parsing the response body text as JSON.

Note: See the Body section for similar methods to extract other types of body content.
Fetch requests are controlled by the connect-src directive of Content Security Policy rather than the directive of the resources it's retrieving.

The fetch() method can optionally accept a second parameter, an init object that allows you to control a number of different settings:.

See fetch() for the full options available, and more details. Note that mode: "no-cors" only allows a limited set of headers in the request:. Content-Type with a value of application/x-www-form-urlencoded, multipart/form-data, or text/plain.

To cause browsers to send a request with credentials included on both same-origin and cross-origin calls, add credentials: 'include' to the init object you pass to the fetch() method. Note:Access-Control-Allow-Origin is prohibited from using a wildcard for requests with credentials: 'include'. In such cases, the exact origin must be provided; even if you are using a CORS unblocker extension, the requests will still fail.

Note: Browsers should not send credentials in preflight requests irrespective of this setting. For more information see: CORS > Requests with credentials. If you only want to send credentials if the request URL is on the same origin as the calling script, add credentials: 'same-origin'. To instead ensure browsers don't include credentials in the request, use credentials: 'omit'.

Additional Notes:

Use fetch() to POST JSON-encoded data. Files can be uploaded using an HTML input element, FormData() and fetch(). Files can be uploaded using an HTML input element, FormData() and fetch(). The chunks that are read from a response are not broken neatly at line boundaries and are Uint8Arrays, not strings. If you want to fetch a text file and process it line by line, it is up to you to handle these complications. The following example shows one way to do this by creating a line iterator (for simplicity, it assumes the text is UTF-8, and doesn't handle fetch errors).

A fetch() promise will reject with a TypeError when a network error is encountered or CORS is misconfigured on the server-side, although this usually means permission issues or similar — a 404 does not constitute a network error, for example. An accurate check for a successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has a value of true.

Differences from jQuery

The code would look something like this:. Instead of passing a path to the resource you want to request into the fetch() call, you can create a request object using the Request() constructor, and pass that in as a fetch() method argument:. Request() accepts exactly the same parameters as the fetch() method.

Headers

  • You can even pass in an existing request object to create a copy of it:. This is pretty useful, as request and response bodies can only be used once. Making a copy like this allows you to effectively use the request/response again while varying the init options if desired.
  • The copy must be made before the body is read. Note: There is also a clone() method that creates a copy.

Both methods of creating a copy will fail if the body of the original request or response has already been read, but reading the body of a cloned response or request will not cause it to be marked as read in the original.

The Headers interface allows you to create your own headers object via the Headers() constructor.
A headers object is a simple multi-map of names to values:.
The same can be achieved by passing an array of arrays or an object literal to the constructor:.
The contents can be queried and retrieved:.
Some of these operations are only useful in ServiceWorkers, but they provide a much nicer API for manipulating headers.
All of the Headers methods throw a TypeError if a header name is used that is not a valid HTTP Header name.
The mutation operations will throw a TypeError if there is an immutable guard (see below).
Otherwise, they fail silently.
A good use case for headers is checking whether the content type is correct before you process it further.
Since headers can be sent in requests and received in responses, and have various limitations about what information can and should be mutable, headers' objects have a guard property.
This is not exposed to the Web, but it affects which mutation operations are allowed on the headers object.
Possible guard values are:.
request: guard for a headers object obtained from a request (Request.headers).
request-no-cors: guard for a headers object obtained from a request created with Request.modeno-cors.
response: guard for a headers object obtained from a response (Response.headers).
immutable: guard that renders a headers object read-only; mostly used for ServiceWorkers.
Note: You may not append or set the Content-Length header on a guarded headers object for a response.
Similarly, inserting Set-Cookie into a response header is not allowed: ServiceWorkers are not allowed to set cookies via synthesized responses.
As you have seen above, Response instances are returned when fetch() promises are resolved.

Aborting a fetch

The most common response properties you'll use are:. Response.status — An integer (default value 200) containing the response status code.

Response.statusText — A string (default value ""), which corresponds to the HTTP status code message. Note that HTTP/2 does not support status messages.