HTTP: Definitive Guide For JavaScript Developers
Tags: http, javascript, networking, webdev
Published: 2023-05-09 14:24:02

## What is a http request? 

Http is the protocol computers use to communicate with each other over the internet. This is the bedrock of the internet. Http requests are how clients communicate with servers(remote or internal).
 
With http requests, clients can send, retrieve, or update data that is hosted on a server. The client also receives a response back from the server with the intended file or error message and status codes depending on whether the request was successful or not. This is known as request-response cycle. 

Here's how a request looks like:
       `GET xxx/http 1.1`

The `GET ` specifies the request type. There are many request types but the most commonly used are:
•	GET—for retrieving data from servers. 
•	POST—for sending new data to the server. 
•	PUT—for updating all parts of an existing data on a server. 
•	PATCH—for updating some parts of an existing data on a server. 
•	DELETE—for deleting a resource on a server. 

The `xxx` part specifies the URL you want to connect to. 
The `http 1.1` specifies the protocol used for the communication. 

### Request Headers
Http requests also have header—request headers. Request headers contain information about the client that is required to establish a connection between the client and the server. 
The payload data include: authorization token, content type, and encoding. 

## How to make http requests in JavaScript 
There are several ways of making request in JavaScript, but we are going to look at the two most popular: `fetch` API and `axios`. 

## Using fetch API 

### Making a GET request using fetch API 
The `fetch()` function takes the URL as a parameter and returns a promise. You can use the `.then()` to receive and manipulate the response. 

```js
fetch('https://example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
```


### Making a POST request using `fetch` API 
The `fetch()` takes a second parameter, which is an object, that specifies the request type, body(containing the data to be sent to the server, usually an object converted to a JSON string using the `JSON.stringify()` method), headers, and other relevant fields. 

```js
const data = { name: 'John', age: 30 };
const options = {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(data),
};

fetch('https://example.com/users', options)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
```


### Making a PUT/PATCH request using fetch API 
The PUT/PATCH request is similar to the POST request. You just have to specify the request type and modify the data accordingly. 

`PUT` request

```js
const formData = new FormData();
formData.append('name', 'John');
formData.append('age', '30');

const options = {
  method: 'PUT',
  body: formData,
};

fetch('https://example.com/users/123', options)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
```

`PATCH` Request 

```javascript
const data = { name: 'John', age: 30 };
const options = {
  method: 'PATCH',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(data),
};

fetch('https://example.com/users/123', options)
  .then(response => console.log(response.json()))
  .catch(error => console.error(error));
```

### Making DELETE requests using fetch
As the name implies, a DELETE requests deletes a resource/data from an endpoint on a server. 

```javascript
const options = {
  method: 'DELETE',
};

fetch('https://example.com/users/123', options)
  .then(response => console.log(response.json()))
  .catch(error => console.error(error));

```


## Using axios
Axios is a third-party library for making http requests. It’s promise-based. It simplifies making http requests and handling the response. 
To use axios, you need to install it. Use this snippet to install axios. 

```
npm install axios
```

### Making a GET request with axios
To make a GET request, you make use of the `.get()`. You can then use the `.then()` to process the data for a successful response or `catch()` to catch errors. This is applicable to all request types. 

```javascript
axios.get('https://example.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
```

### Making a POST request with axios
To make a POST request, you make use of the `post()`. The `post()` takes URL, data to be sent, and an optional config object—more on that later. 
The data to be sent is usually stored in an object. You handle the response in a similar way. 

```javascript
const data = { name: 'John', age: 30 };
const options = {
  headers: { 'Content-Type': 'application/json' },
};

axios.post('https://example.com/users', data, options)
  .then(response => console.log(response.data))
  .catch(error => console.error(error));

```
### Making PUT/PATCH request with axios
Making PUT/PATCH request is similar to that POST, the difference is in the method used; PUT—`put()` and PATCH—`patch()`. 

`PUT` request

```javascript
const formData = new FormData();
formData.append('name', 'John');
formData.append('age', '30');

axios.put('https://example.com/users/123', formData)
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
```

`PATCH` request 

```javascript
const data = { name: 'John', age: 30 };
const options = {
  headers: { 'Content-Type': 'application/json' },
};

axios.patch('https://example.com/users/123', data, options)
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
```

### Making a DELETE request using axios
To make a DELETE request, you make use of the `delete()` method. You only have to specify the endpoint. 

```js
axios.delete('https://example.com/users/123')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
```

## Adding Headers to requests in axios
You can add request headers in axios by passing an object with a `headers` property as a second parameter inside of GET/DELETE request and third parameter inside of POST/PUT/PATCH request. 
 

```js
const headers = { 'Authorization': 'Bearer my-token' };
axios.get('https://example.com/data', { headers })
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
```

You can also define a config object and add your `headers` as a property which is an object containing other fields. Then, you can pass it into the various request methods. 

```javascript
const config = {
  headers: { 'Authorization': 'Bearer my-token' },
};

axios.post('https://example.com/users', data, config)
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
```

### Default headers
Your application may have multiple API requests, and you may want to set request headers for all of them. Instead of adding the headers to each request, you can put them as default headers, and they will apply to all the requests. To do so, use the `defaults.headers` property of the `axios` object.

```javascript
axios.defaults.baseURL = 'https://example.com/api';
axios.defaults.headers.common['Authorization'] = 'Bearer my-token';

// Make requests using the regular axios object
axios.get('/data')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));

axios.post('/users', data)
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
```

In this example, we set the default headers using the `axios.defaults.headers.common` object. We set the `Authorization` header to `Bearer my-token`. We also set the default base URL using the `axios.defaults.baseURL` property. Then, we use the regular `axios` object to make API requests, and the default headers will be applied to all of them.

---

## Conclusion 
In this article, we have learned what http requests are, types of http requests, and how to make http requests in JavaScript. We learned how to use the browser built-in `fetch` API and axios—third-party http client library. 

With our new knowledge, we can now communicate with servers from our frontend application. 

If you found value in this article, like and share. 

Also, follow me for more content on front-end topics and web development.