In JavaScript, the fetch()
method is used to make asynchronous requests to the server and load the information that is returned by the server onto the web pages.
fetch(URL, options);
The fetch()
method accepts the following two parameters.
URL
: The URL on which the request is to be made.Options
: An object which consists of additional properties that can be sent to the server. It is optional.The fetch()
method returns a promise that can either be resolved or not. Thus, this method always returns a value and the only possible case where it may fail to return anything is a server error.
Let’s make some requests to a public URL and see how fetch works in detail.
The fetch method works in a chain of multiple then()
methods and one error()
method. The error()
method will only be called if any error occurs while the request is made.
The format of returned data can be JSON or XML. Here, we have explicitly converted the returned data to JSON format using json(
) method and logged it into the console. Thus, we can get any data we want from the server via fetch()
.
The default method of fetch()
is GET. If needed, we can also make a POST, PUT and DELETE method request as well. Below is an example of fetch()
using the POST method.