Javascript's Fetch API

Fetch API allows us to fetch the resources across the Network similar to XHR. But the new API provides more powerful and flexible feature set. It has a new standard jam-packed way to make the request, which also uses promises.

Before starting with fetch API we have to understand what is the difference between fetch and XHR or jquery ajax.

Difference Between Fetch and XHR

XHR Fetch
Can't perform no-cors requests Can perform no-cors requests
Can't use the Cache API with the request and response object Can use the Cache API with the request and response object
can't return FormData instances can return FormData instances

Here is one article where you can see more detail on fetch API : That's so fetch!

Fetch API Syntax

By default fetch API uses the GET verb which syntax is as follows

fetch(url).then(() => {  
 ...  
}).catch(() => {  
 ...  
}) 

Example

If we want to send post call from the fetch API then also you can do here is the example of post call

const url = '<URL>';  
  
let data = {  
 name: 'sourabh somani',  
 email: 'sourabh_somani2010@hotmail.com',  
 mobile: '9314554546'  
};  
  
fetch(url, {  
 method: 'POST',  
 body: data,  
 headers: new Headers()  
}).then(function(res) {  
 // do whatever you want to do after success    
}).catch(function(err) {  
 // Error when API send any error    
}); 

To know more about fetch API here are the link of couple of articles

🙂🙂🙂

Sourabh Somani
He is Microsoft MVP & C# Corner MVP. His core competencies include Mobile and web applications development using .NET, Python, Node.js, C#, JavaScript, jQuery, SQL Server, NoSQL, MongoDB, and Angular.
Chittorgarh, Rajasthan, India