The JavaScript Fetch API is an interface that accesses and manipulates components of the protocol (a machine of policies that imply how data is exchanged among or within computer systems), which include requests and responses. In our internet site, Okpediaa you may get to learn about Javascript Fetch APIs.
Table of Contents
What is Fetch?
Fetch affords a effective, logical manner to fetch sources asynchronously. Fetch enables a person to create HTTP requests, which can be without difficulty treated using JavaScript guarantees.
Basic Fetch Request
The maximum easy use of Fetch is a GET request, which can be executed like this:
Copied!fetch('https://api.example.com/data');
Handling Responses
Fetch returns a Promise that resolves to the response of a request, whether or not it is a hit or now not.
Copied!fetch('https://api.example.com/data') then ((response) => console.log(response));
Checking Successful Fetch
Frequently, you may need to test if the request became successful.
Here’s how to do it:
Copied!fetch('https://api.example.com/data') .then((response) => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); });
Handling JSON Data
To extract the JSON body content from the response, we use the json() approach:
Copied!fetch('https://api.example.com/data') .then((response) => response.json()) .then((data) => console.log(data));
Error Handling
If a network error takes place, the capture() is brought on.
Copied!fetch('https://api.example.com/data') .then((response) => response.json()) .then((data) => console.log(data)) .catch((error) => console.error('There has been a problem with your fetch operation:', error), );
Fetch POST Request
Fetch isn’t just for GET requests. you could use it to send other styles of requests, like put up
Copied!fetch('https://api.example.com/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: '200' }), });
Leave a Reply