FETCH API
Fetch API provide to make the network request with promises(response and rejected) and they have a much simpler and cleaner snippet of API compare to XMLHttpRequest, its also avoid the remember the complex hell API of XMLHttpRequest.
Fetch API is available in "Service Worker" to fetch a resource from another domain. Its global scope since in chrome 40 and window scope since in chrome 42.
In fetch() we have one mandatory argument for a path to fetch the resource which you want. its returns a Promise that Response when is resolve or rejected, if its resolve then they fetch() the resource successfully, else it is not resolved to mean it rejected then they not able to fetch the resource successfully.
lets, now see time to see a code to get in mind about how to use fetch() in your code.
lets, now see time to see a code to get in mind about how to use fetch() in your code.
fetch('path', { init })
.then(resolve)
.catch(reject)
In the above example, we set a path(for fetching resource) and init options, then block is run when the fetch() is successfully fetched the resource from the server. the catch block is run when it is not able to fetch a resource.
Here we also have some optionally pass to an init option as the second argument to customize the fetch according to your requirement.
Here we also have some optionally pass to an init option as the second argument to customize the fetch according to your requirement.
In init options, we give or use many options such as below:
HANDLE ERROR:
Fetch API is useful to handle the error, let us suppose we fetch the file or resource from the server but it doesn`t exist in the server they could give the 404 error on a response. however, thanks to promises because they easily handle those error with cleaner and understandable code.
RESOURCES:
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json",
// "Content-Type": "application/x-www-form-urlencoded",
},
redirect: "follow", // manual, *follow, error
referrer: "no-referrer", // no-referrer, *client
body: JSON.stringify(data), // body data type must match "Content-Type" header
This above some init options is helpful to fetch the resource with some customization.HANDLE ERROR:
Fetch API is useful to handle the error, let us suppose we fetch the file or resource from the server but it doesn`t exist in the server they could give the 404 error on a response. however, thanks to promises because they easily handle those error with cleaner and understandable code.
RESOURCES:
Comments
Post a Comment