This Is Your Complete Guide For Sending Requests Using fetch in JS
Tags: javascript, typescript, beginners, webdev
Published: 2021-08-22 00:01:12

Hi, I'm [Aya Bouchiha](developer.aya.b@gmail.com), 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

```js
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

```js
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

```js
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

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

## POST request using async and await

```js
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

```js
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:

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

## Sending a PUT request using async & await

```js
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:

```js
{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

```js
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

```js
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!