DEV Community

Cover image for This Is Your Complete Guide For Sending Requests Using fetch in JS
Aya Bouchiha
Aya Bouchiha

Posted on • Updated on

This Is Your Complete Guide For Sending Requests Using fetch in JS

Hi, I'm Aya Bouchiha, on this beautiful day, I'm going to discuss sending requests in javascript using fetch.

What's GET request

GET: is a request used for getting or retrieving data or information from a specified server.

Code using then and catch

const getTodo = (id) => {
    const url = `https://jsonplaceholder.typicode.com/todos/${id}`;
    fetch(url)
        .then((response) => response.json())
        .then((todo) => console.log(todo))
        .catch((e) => console.log('something went wrong ;(', e));
};
getTodo(1);
Enter fullscreen mode Exit fullscreen mode

Code using async and await

Method 1

const getTodo = async (id) => {
    const url = `https://jsonplaceholder.typicode.com/todos/${id}`;
    try {
        const response = await fetch(url);
        const data = await response.json();
        console.log(data);
    } catch (e) {
        console.log('something went wrong :(', e);
    }
};
getTodo(1);
Enter fullscreen mode Exit fullscreen mode

Method 2

const getTodo = async (id) => {
    const url = `https://jsonplaceholder.typicode.com/todos/${id}`;
    try {
        const data = await (await fetch(url)).json();
        console.log(data);
    } catch (e) {
        console.log('something went wrong :(', e);
    }
};
getTodo(1);
Enter fullscreen mode Exit fullscreen mode

What's POST request

POST: is a request that is used for sending information or data to a specific server.

POST request using then and catch

const postTodo = (todo) => {
  fetch('https://jsonplaceholder.typicode.com/posts',{
    method:'POST',
    body:JSON.stringify(todo),
    headers:{
      'header-name':'header-value'
    }
  }).then(response => response.json())
    .then(data => console.log(data) /* {id:101} */)
    .catch(e => console.log('something went wrong :(', e))
}
const data = {
  title: 'buy food',
  body: "buy healthy food",
  userId: 8,
};
postTodo(data);
Enter fullscreen mode Exit fullscreen mode

POST request using async and await

const postTodo = async (todo) => {
  try {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts',{
    method:'POST',
    headers:{
      'header-name': 'header-value'
    },
    body:JSON.stringify(todo)
  })
  const data = await response.json();
  console.log(data); // {id:101}
  }catch(e){
    console.log('something went wrong :(', e)
  }
}
const data = {
  title: 'buy food',
  body: "buy healthy food",
  userId: 8,
};
postTodo(data);
Enter fullscreen mode Exit fullscreen mode

What's the PUT request

PUT: is a request used for creating or updating a resource in a specific server.

Sending a PUT request using then & catch

const putTodo = (todo) => {
    const method = 'PUT';
    const headers = {
        'Content-type': 'application/json; charset=UTF-8',
        'header-name': 'header-value',
    };
    fetch('https://jsonplaceholder.typicode.com/posts/1', {
        method,
        headers,
        body: JSON.stringify(todo),
    })
        .then((response) => response.json())
        .then((data) => console.log(data))
        .catch((e) => console.log('something went wrong :(', e));
};
const data = {
    id: 1,
    title: 'this is a title',
    body: 'body!',
    userId: 13,
};
putTodo(data);
Enter fullscreen mode Exit fullscreen mode

Console:

{id: 1, title: "this is a title", body: "body!", userId: 13}
Enter fullscreen mode Exit fullscreen mode

Sending a PUT request using async & await

const putTodo = async (todo) => {
    const method = 'PUT';
    const headers = {
        'Content-type': 'application/json; charset=UTF-8',
        'header-name': 'header-value',
    };
    try {
        const response = await fetch(
            'https://jsonplaceholder.typicode.com/posts/1',
            { method, headers, body: JSON.stringify(todo) },
        );
        const data = await response.json();
        console.log(data);
    } catch (e) {
        console.log('something went wrong :(', e);
    }
};
const data = {
    id: 1,
    title: 'this is a title',
    body: 'body!',
    userId: 13,
};
putTodo(data);
Enter fullscreen mode Exit fullscreen mode

Console:

{id: 1, title: "this is a title", body: "body!", userId: 13}
Enter fullscreen mode Exit fullscreen mode

What's DELETE request

DELETE: is a request used to delete a specific resource in a server.

Sending DELETE request using then & catch

const id = 5;
const deleteTodo = (todoId) => {
  const url = `https://jsonplaceholder.typicode.com/posts/${todoId}`;
  const method  = 'DELETE'
  fetch(url,{method})
  .then(response => console.log(response.status)/*200*/)
  .catch(e=> console.log('something went wrong',e))
};
deleteTodo(id);
Enter fullscreen mode Exit fullscreen mode

Sending DELETE request using async and await

const id = 5;
const deleteTodo = async (todoId) => {
  const url = `https://jsonplaceholder.typicode.com/posts/${todoId}`;
  const method  = 'DELETE';
  try {
    const response = fetch(url, {method});
    console.log((await response).status)// 200
  }catch(e){
    console.log('something went wrong', e);
  }
} 
deleteTodo(id);
Enter fullscreen mode Exit fullscreen mode

Have a good day!

Oldest comments (5)

Collapse
 
ayabouchiha profile image
Aya Bouchiha

thank you a lot Anjan

Collapse
 
aatmaj profile image
Aatmaj • Edited

I loved your starting line! "on this beautiful day..."

Collapse
 
ayabouchiha profile image
Aya Bouchiha

Glad to hear that 😊

Collapse
 
wkylin profile image
wkylin.w

postTodo(); ===>>> postTodo(data);

Collapse
 
ayabouchiha profile image
Aya Bouchiha

My bad, thank you for reminding me