DEV Community

Mrityunjay-Palled
Mrityunjay-Palled

Posted on

fetch() in JavaScript

The fetch() method can be used as a replacement for XMLHttpRequest. It is used to get the data from the server asynchronously. The major
The difference between fetch() and XMLHttpRequest is that XMLHttpRequest uses callbacks and fetch() uses promises. Before going further some prior knowledge of promises is required.

Fetching data from a REST API:

Image description

In most cases, fetch() takes only one parameter, which is the request URL. In the above example, the "then" block is executed if the promise returned by fetch() is resolved; otherwise, the "catch" block is executed if the promise is rejected. Now let's see what other parameters we can pass to the fetch() method.

Image description

In the above example we can see that we are passing method and header properties along with request URL. method property can be any HTTP method ('GET','POST','PUT','DELETE','PATCH') and header property can be any suitable MIME type.

Posting data to a REST API:

Image description

In the above example, we are posting the data to an API, and while posting the data to an API, we added an additional body property to the fetch() method. The body property takes the data to be posted; in our case, the data to be posted is stored in the "_payload".

Image description

As we can see, the data is successfully posted to an API.

Top comments (0)