Axios-Sheet
Fri Jul 21 2023 09:33:20 GMT+0000 (Coordinated Universal Time)
Saved by @menaheero
**Summary of Axios - A Powerful HTTP Client for JavaScript**
Axios is a popular JavaScript library used for making HTTP requests from the browser or Node.js applications. It provides an easy-to-use and flexible interface to interact with APIs and fetch data. As a software developer, understanding Axios is essential for building modern web applications that communicate with backend servers.
**1. Installation and Setup:**
To use Axios in your project, you need to install it first. You can do this using npm or yarn.
Example:
```bash
npm install axios
```
or
```bash
yarn add axios
```
**2. Making GET Requests:**
Axios makes it simple to send GET requests to a server and handle the responses.
Example:
```javascript
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
```
**3. Making POST Requests:**
You can use Axios to send data to the server using POST requests.
Example:
```javascript
const data = { name: 'John', email: 'john@example.com' };
axios.post('https://api.example.com/users', data)
.then(response => {
console.log('User created:', response.data);
})
.catch(error => {
console.error('Error creating user:', error);
});
```
**4. Handling Errors:**
Axios allows you to handle different types of errors that might occur during the HTTP request.
Example:
```javascript
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
if (error.response) {
// The server responded with a status code other than 2xx.
console.error('Request failed with status:', error.response.status);
} else if (error.request) {
// The request was made but no response was received.
console.error('No response received:', error.request);
} else {
// Something happened in setting up the request that triggered an error.
console.error('Error:', error.message);
}
});
```
**5. Setting Headers:**
You can set custom headers in your requests, such as authorization tokens or content types.
Example:
```javascript
const headers = {
Authorization: 'Bearer YOUR_ACCESS_TOKEN',
'Content-Type': 'application/json',
};
axios.post('https://api.example.com/data', data, { headers })
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error:', error.message);
});
```
**6. Performing Concurrent Requests:**
Axios allows you to perform multiple requests concurrently using `axios.all` and `axios.spread`.
Example:
```javascript
const request1 = axios.get('https://api.example.com/data/1');
const request2 = axios.get('https://api.example.com/data/2');
axios.all([request1, request2])
.then(axios.spread((response1, response2) => {
console.log('Response 1:', response1.data);
console.log('Response 2:', response2.data);
}))
.catch(error => {
console.error('Error:', error.message);
});
```
**7. Interceptors:**
You can use Axios interceptors to transform request and response data globally.
Example:
```javascript
axios.interceptors.request.use(config => {
// Modify the config before the request is sent.
config.headers['X-Requested-With'] = 'XMLHttpRequest';
return config;
});
axios.interceptors.response.use(response => {
// Modify the response data before it is resolved.
return response.data;
});
```
**8. Cancellation:**
Axios supports request cancellation to abort ongoing requests.
Example:
```javascript
const source = axios.CancelToken.source();
axios.get('https://api.example.com/data', { cancelToken: source.token })
.then(response => {
console.log(response.data);
})
.catch(error => {
if (axios.isCancel(error)) {
console.log('Request canceled:', error.message);
} else {
console.error('Error:', error.message);
}
});
// Cancel the request (e.g., on component unmount).
source.cancel('Request canceled due to component unmount.');
```
**Cheatsheet:**
Here's a quick cheatsheet summarizing the most important concepts and commands in Axios:
```plaintext
1. Installation and Setup:
npm install axios
2. Making GET Requests:
axios.get(url[, config])
3. Making POST Requests:
axios.post(url[, data[, config]])
4. Handling Errors:
axios.get(url).then().catch()
5. Setting Headers:
const headers = { key: 'value' };
axios.post(url, data, { headers })
6. Performing Concurrent Requests:
axios.all([request1, request2]).then(axios.spread())
7. Interceptors:
axios.interceptors.request.use()
axios.interceptors.response.use()
8. Cancellation:
const source = axios.CancelToken.source();
axios.get(url, { cancelToken: source.token });
source.cancel('Reason for cancellation');
```
With this summary and cheatsheet, you have all the essential information to confidently use Axios for handling HTTP requests in your software development projects. Happy coding!
Comments