This Is You 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 us…


This content originally appeared on DEV Community and was authored by Aya Bouchiha

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);

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);

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);

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();

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);

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);

Console:

{id: 1, title: "this is a title", body: "body!", userId: 13}

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);

Console:

{id: 1, title: "this is a title", body: "body!", userId: 13}

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);

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);

Have a good day!


This content originally appeared on DEV Community and was authored by Aya Bouchiha


Print Share Comment Cite Upload Translate Updates
APA

Aya Bouchiha | Sciencx (2021-08-22T00:01:12+00:00) This Is You Complete Guide For Sending Requests Using fetch in JS. Retrieved from https://www.scien.cx/2021/08/22/this-is-you-complete-guide-for-sending-requests-using-fetch-in-js/

MLA
" » This Is You Complete Guide For Sending Requests Using fetch in JS." Aya Bouchiha | Sciencx - Sunday August 22, 2021, https://www.scien.cx/2021/08/22/this-is-you-complete-guide-for-sending-requests-using-fetch-in-js/
HARVARD
Aya Bouchiha | Sciencx Sunday August 22, 2021 » This Is You Complete Guide For Sending Requests Using fetch in JS., viewed ,<https://www.scien.cx/2021/08/22/this-is-you-complete-guide-for-sending-requests-using-fetch-in-js/>
VANCOUVER
Aya Bouchiha | Sciencx - » This Is You Complete Guide For Sending Requests Using fetch in JS. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/08/22/this-is-you-complete-guide-for-sending-requests-using-fetch-in-js/
CHICAGO
" » This Is You Complete Guide For Sending Requests Using fetch in JS." Aya Bouchiha | Sciencx - Accessed . https://www.scien.cx/2021/08/22/this-is-you-complete-guide-for-sending-requests-using-fetch-in-js/
IEEE
" » This Is You Complete Guide For Sending Requests Using fetch in JS." Aya Bouchiha | Sciencx [Online]. Available: https://www.scien.cx/2021/08/22/this-is-you-complete-guide-for-sending-requests-using-fetch-in-js/. [Accessed: ]
rf:citation
» This Is You Complete Guide For Sending Requests Using fetch in JS | Aya Bouchiha | Sciencx | https://www.scien.cx/2021/08/22/this-is-you-complete-guide-for-sending-requests-using-fetch-in-js/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.