Trusted answers to developer questions

What is fetch() in JavaScript?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

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.

Syntax

fetch(URL, options);

Parameters

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.

Return value

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.

Code

Let’s make some requests to a public URL and see how fetch works in detail.

Console

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.

Console

RELATED TAGS

javascript
fetch
asynchronous

CONTRIBUTOR

Shubham Singh Kshatriya
Did you find this helpful?