5.1 Fetch API
For making HTTP requests in JavaScript, two libraries are commonly used: the built-in fetch function and the external Axios library. Both offer powerful and flexible capabilities for interacting with APIs and other web resources.
Fetch API is a built-in way in browsers to make HTTP requests. It's based on promises and provides a flexible and modern approach to handling network requests.
Simple fetch request syntax:
let promise = fetch(url, {method, headers,
body})
Main Fetch concepts:
fetch(url, options)
: the main method for making HTTP requests- Returns a promise that resolves to a Response object
Example of a simple GET request using Fetch:
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
if (!response.ok) {
throw new Error('Network error: received an incorrect response from the server');
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Request error: ', error);
});
Example of a POST request using Fetch:
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('Request error: ', error);
});
Fetch Settings
Fetch API allows configuring various request parameters through the options
object, such as method, headers, request body, and more.
const options = {
method: 'GET', // or 'POST', 'PUT', 'DELETE', etc.
headers: {
'Content-Type': 'application/json'
},
// body: JSON.stringify(data) // used for POST and PUT requests
};
fetch('https://jsonplaceholder.typicode.com/posts/1', options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Request error: ', error));
5.2 Axios Library
Axios is a popular library for making HTTP requests in JavaScript. It offers a more convenient and functional API compared to the native Fetch API and supports many additional features, such as automatic JSON conversion, timeout handling, request cancellation, and support for older browsers.
Installing Axios
Axios can be installed via npm or included through a CDN.
Installation via npm:
npm install axios
Using in Node.js or with module bundlers (e.g., Webpack):
// For CommonJS
const axios = require('axios');
// For ES6 modules
import axios from 'axios';
Including via CDN in the browser:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Simple GET request syntax:
let promise = axios.get(url)
Simple POST request syntax:
let promise = axios.post(url, data, config)
Main Axios concepts:
- axios(config): the main method for making HTTP requests
- Takes a configuration object, which can include
url
,method
,headers
,data
, and other parameters. - Shortcut methods: Axios provides methods for each HTTP method (
axios.get
,axios.post
,axios.put
,axios.delete
, etc.), simplifying the execution of corresponding requests. - Promises: all Axios methods return a Promise that resolves to the response object or is rejected in case of an error.
Simple GET request syntax with response and error handling:
axios.get(url)
.then(response => {
// Handle successful response
})
.catch(error => {
// Handle error
});
Simple POST request syntax with response and error handling:
axios.post(url, data, config)
.then(response => {
// Handle successful response
})
.catch(error => {
// Handle error
});
Example of a simple GET request using Axios:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Request error: ', error);
});
Example of a POST request using Axios:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Request error: ', error);
});
5.3 Configuring Axios
Axios Settings
Axios lets you configure HTTP requests via the config
object, which includes parameters like url
, method
, headers
, and data (data
).
Here's a basic example of request configuration:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
const config = {
method: 'get', // can be 'get', 'post', 'put', 'delete', etc.
url: 'https://jsonplaceholder.typicode.com/posts/1',
headers: {
'Content-Type': 'application/json' // Header to specify data type
},
// data: JSON.stringify(data) // Used for POST and PUT requests to pass request body
};
axios(config)
.then(response => console.log(response.data))
.catch(error => console.error('Request error: ', error));
Additional Axios Features:
- Query parameters: can be passed in the URL.
- Request cancellation: using
AbortController
. - Timeouts: setting a waiting time for the request.
Example of using query parameters:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
axios.get('https://jsonplaceholder.typicode.com/posts', {
params: {
userId: 1 // Query parameters are passed via the params object
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Request error: ', error);
});
5.4 Comparing Fetch and Axios
Let's compare Fetch and Axios based on key metrics:
1. Ease of Use:
- Fetch: easy to use for basic operations but requires additional handling for complex scenarios (e.g., JSON transformation, timeout handling).
- Axios: offers a more convenient and powerful API for performing complex requests.
2. JSON Support:
- Fetch: requires explicit
response.json()
call to parse the response body to JSON. - Axios: automatically parses JSON responses.
3. Timeouts:
- Fetch: no built-in support for timeouts. Timeout implementation requires using
AbortController
or wrappers. - Axios: supports timeout configuration.
4. Interceptors:
- Fetch: does not support request and response interceptors.
- Axios: allows the use of interceptors to perform logic before and after sending a request.
Example of interceptors in Axios
Interceptors allow performing specific actions before sending a request or after receiving a response:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
// Adding a request interceptor
axios.interceptors.request.use(config => {
console.log('Request sent to server: ', new Date());
return config;
}, error => {
return Promise.reject(error);
});
// Adding a response interceptor
axios.interceptors.response.use(response => {
console.log('Response received from server: ', new Date());
return response;
}, error => {
return Promise.reject(error);
});
// Example request with interceptors
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(response => console.log(response.data))
.catch(error => console.error('Request error: ', error));
Parallel Requests with Axios
Using Axios, you can easily make parallel requests and handle the results with Promise.all()
:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Promise.all([
axios.get('https://jsonplaceholder.typicode.com/todos/1'),
axios.get('https://jsonplaceholder.typicode.com/todos/2')
])
.then(responses => {
responses.forEach(response => {
console.log(response.data);
});
})
.catch(error => console.error('Request error: ', error));
GO TO FULL VERSION