Skip to content
the poor coder

fetch api in js

Poor Man
Published
Reading time
2 min read
On this page

Fetch API in JavaScript#

Fetch API is a modern way of making network requests in JavaScript. It provides a global fetch() method that returns a Promise which resolves to the Response object representing the response to the request.

Syntax#

Text

fetch(resource [, options])
    .then(response => { ... })
    .catch(error => { ... });
  • resource - The URL of the resource to request.
  • options (optional) - An object containing request options like headers, method, body, etc.
  • response - The Response object returned by the server.
  • error - The error object thrown if the request fails.

Fetch Request Methods#

The most commonly used HTTP request methods are:

  • GET - The HTTP GET method is used to retrieve data from the server.
  • POST - The HTTP POST method is used to submit data to the server.
  • PUT - The HTTP PUT method is used to update an existing resource on the server.
  • DELETE - The HTTP DELETE method is used to delete a resource from the server.

Example#

Let's see an example of how to make a GET request using fetch API:

Text

fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error));

In the above example, we are making a GET request to the JSONPlaceholder API to fetch the first post. The .json() method is used to parse the JSON response and convert it into a JavaScript object. The returned data is then logged to the console.

Multiple Ways to Use Fetch API#

There are multiple ways to use Fetch API depending on the type of request and the data being sent. Here are some examples:

  • Making a POST request with JSON data:
Text

fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        title: 'foo',
        body: 'bar',
        userId: 1
    })
})
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error));
  • Making a PUT request with form data:
Text

const formData = new FormData();
formData.append('title', 'foo');
formData.append('body', 'bar');
formData.append('userId', 1);

fetch('https://jsonplaceholder.typicode.com/posts/1', {
    method: 'PUT',
    body: formData
})
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error));

These are just a few examples of how Fetch API can be used in JavaScript. It provides a modern and flexible way of making network requests and can be used in place of traditional methods like XMLHttpRequest.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC