
Hi 👋
Fetching data from a website, or even a local inside your code can be a real headache sometimes. There are many methods that we generally use to get and use data from external sources or files inside our projects. We can even getOur Data from Google Sheetsif we use the correct methods. Here we are going to discuss about theFetch API today.
About Fetch API
The Fetch API is an interface that allows you to make HTTP requests to the server from web browsers.
- If you have worked with XMLHttpRequest (XHR) object.
- Fetch API can perform all the tasks as the XHR object does.
- Fetch API is much simpler and cleaner.
- It uses the promise to deliver more flexible features to make requests to servers from the web browser.
Sending a Request
Thefetch()
method is available in the global scope that instructs the web browsers to send a request to a URL.
- The
fetch()
requires only one parameter, the URL of the resource that you want to fetch. - When the request completes, the promise resolves into a Response object.
letresponse_obj_var=fetch(URL);
Reading the response
Thefetch()
method returns a promise so you can use thethen()
andcatch()
methods to handle it
fetch(URL).then((response)=>{//handle the responseconsole.log(response)}).catch((error)=>{//handle the errorconsole.warn(error)});
Handling Data
If the contents of the response are in the raw format, you use thetext()
method.
Thetext()
method returns a Promise that resolves with the complete contents of the fetched resource.
fetch('/readme.txt').then(response=>response.text()).then(data=>console.log(data));
Besides thetext()
method, the response object has different other methods, such asjson()
,blob()
,formData()
,arrayBuffer()
and many more, to handle the respective type of data. In practice, you often useasync/await
with thefetch()
method like this:
asyncfunctionfetchDataFunc(){letresponse=awaitfetch('/readme.txt');letdata=awaitresponse.txt();console.log(data);}
Handling the status codes
The response object provides the status code and status text via the status and statusText properties.
asyncfunctionfetchDataFunc(){letresponse=awaitfetch('/readme.txt');console.log(response.status);// returns 200console.log(statusText);// returns OKif(response.status===200){letdata=awaitresponse.text()// handle data}}fetchDataFunc();
I hope you would have liked this article. Do comment below or mail me atmursalfurqan@gmail.com to let me know what you want to read next week.
Till then, have an amazing weekend and Happy Coding 🎉.
Top comments(1)
For further actions, you may consider blocking this person and/orreporting abuse