Get started with Axios easily: HTTP tool in front-end development

Preface

In web development, data communication with the server is a task that every front-end engineer needs to face. Axios, as an excellent HTTP library, provides a set of simple and powerful tools to handle this task. Let us embark on a learning journey with Axios and discover its charm in front-end development.

Why choose Axios

Axios is a modern Promise-based HTTP library for sending HTTP requests in browsers and Node.js environments. Here are some of the advantages of Axios over other HTTP libraries to explain why it is one of the top choices for front-ends:

1. Simple use:

Axios provides a simple, intuitive API that makes sending HTTP requests very easy. It supports Promise and allows the use of async/await syntax, making the code clearer and easier to understand.

// 示例:发送 GET 请求
axios.get('/api/data')
  .then(response => {
    
    
    console.log(response.data);
  })
  .catch(error => {
    
    
    console.error(error);
  });

2. Functional wealth:

Axios provides a rich set of features, including interceptors, cancellation of requests, automatic conversion of JSON data, client endpoint validation, and more. These features make it easier to handle complex requests and responses.

// 示例:使用拦截器处理请求和响应
axios.interceptors.request.use(config => {
    
    
  // 在请求发送前做些什么
  return config;
}, error => {
    
    
  // 对请求错误做些什么
  return Promise.reject(error);
});

axios.interceptors.response.use(response => {
    
    
  // 对响应数据做些什么
  return response;
}, error => {
    
    
  // 对响应错误做些什么
  return Promise.reject(error);
});

3. Widely supported browsers and environments:

Axios can be used not only in the browser, but also in the Node.js environment. It uses some commonly supported features in browsers and also provides some adaptations in Node.js.

4. Spanning support:

Axios supports handling cross-domain requests in requests, and you can set relevant information about cross-domain requests through configuration options. This is important for accessing APIs from different domains from front-end applications.

// 示例:设置跨域请求的相关配置
axios.get('https://api.example.com/data', {
    
     withCredentials: true });

5. Shrine district activity:

Axios has an active community support, updates are frequent, and issues are resolved quickly. This also makes it one of the preferred HTTP libraries for many front-end developers.

6. Friendliness in handling errors:

Axios provides easy-to-understand error handling mechanisms. When a request fails, it can return detailed error information to facilitate troubleshooting and processing by developers.

7. Support for concurrent requests:

Axios allows multiple requests to be sent at once via concurrent requests, and responses are processed uniformly when all requests are completed.

// 示例:并发请求
axios.all([
  axios.get('/api/data1'),
  axios.get('/api/data2')
])
  .then(axios.spread((response1, response2) => {
    
    
    console.log(response1.data, response2.data);
  }))
  .catch(error => {
    
    
    console.error(error);
  });

To sum up, Axios has become one of the preferred HTTP libraries in front-end development due to its simplicity and ease of use, rich functions, cross-environment support, cross-domain processing, and active community. Its design flexibility and scalability enable it to meet various complex front-end HTTP request requirements.

Installation and Reference

Axios can be installed through npm or CDN and introduced into the project. The following are examples of the two methods:

1. Install Axios using npm:

First, make sure npm has been initialized in your project. If not, you can initialize it with the following command:

npm init -y

Then, execute the following command in the project directory to install Axios:

npm install axios

After the installation is complete, you can introduce Axios into the JavaScript file in your project:

// 在需要使用 Axios 的文件中引入
import axios from 'axios';

// 现在可以使用 axios 发送 HTTP 请求了
axios.get('/api/data')
  .then(response => {
    
    
    console.log(response.data);
  })
  .catch(error => {
    
    
    console.error(error);
  });

2. Use CDN to introduce Axios:

Add the following CDN link in the HTML file:

<!-- 在项目的 HTML 文件中引入 Axios CDN -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Then, you can use the global axios object directly in your JavaScript file:

// 直接使用全局的 axios 对象
axios.get('/api/data')
  .then(response => {
    
    
    console.log(response.data);
  })
  .catch(error => {
    
    
    console.error(error);
  });

Whether you choose to install it using npm or bring it in via a CDN, Axios will become a dependency in your project, and you can use it anywhere in your project to handle HTTP requests. Remember to make corresponding configurations according to the needs of the project and the actual situation, such as setting basic URLs, interceptors, etc.

GET and POST requests

Axios provides a simple API to send GET and POST requests, supports passing parameters in the request, and can handle the response. Here's an example of using Axios to make GET and POST requests:

1. GET request:

// 引入 Axios
import axios from 'axios';

// 发起 GET 请求
axios.get('/api/data', {
    
    
  params: {
    
    
    // 传递参数
    key1: 'value1',
    key2: 'value2',
  },
})
  .then(response => {
    
    
    // 处理响应数据
    console.log(response.data);
  })
  .catch(error => {
    
    
    // 处理错误
    console.error(error);
  });

In the above code, theaxios.get method accepts two parameters: the requested URL and a configuration object. The params field in the configuration object is used to pass the parameters of the GET request.

2. POST request:

// 引入 Axios
import axios from 'axios';

// 发起 POST 请求
axios.post('/api/data', {
    
    
  // 请求体数据
  key1: 'value1',
  key2: 'value2',
})
  .then(response => {
    
    
    // 处理响应数据
    console.log(response.data);
  })
  .catch(error => {
    
    
    // 处理错误
    console.error(error);
  });

In a POST request, theaxios.post method also accepts two parameters: the requested URL and the request body data. The data in the request body can be an object, and Axios will automatically convert it into JSON format and send it. If you need to use another format, you can configure it using the headers field.

3. Process the response:

When processing the response, you can process the response data according to your needs, such as parsing JSON, obtaining specific fields, etc.

axios.get('/api/data')
  .then(response => {
    
    
    // 获取响应头
    const contentType = response.headers['content-type'];

    // 判断响应类型
    if (contentType && contentType.includes('application/json')) {
    
    
      // 解析 JSON 数据
      console.log(response.data);
    } else {
    
    
      console.error('Invalid content type');
    }
  })
  .catch(error => {
    
    
    console.error(error);
  });

In the above code, we obtain the response header through response.headers, determine whether the response type is JSON, and process it accordingly.

Axios also supports the use of interceptors to process requests and responses globally, such as adding common request headers, handling errors, etc. This makes using Axios in your projects more convenient and flexible.

Process response data

Axios provides flexible ways to handle various types of response data, including JSON, text, blobs, and more. Here are examples of handling different types of response data:

1. Process JSON data:

// 引入 Axios
import axios from 'axios';

// 发起 GET 请求,预期响应是 JSON 数据
axios.get('/api/json-data')
  .then(response => {
    
    
    // 在响应拦截器中处理 JSON 数据
    console.log(response.data);
  })
  .catch(error => {
    
    
    // 处理错误
    console.error(error);
  });

By default, Axios will automatically parse the JSON response, and you can get the parsed data directly through response.data.

2. Process text data:

// 引入 Axios
import axios from 'axios';

// 发起 GET 请求,预期响应是文本数据
axios.get('/api/text-data', {
    
    
  responseType: 'text', // 指定响应类型为文本
})
  .then(response => {
    
    
    // 在响应拦截器中处理文本数据
    console.log(response.data);
  })
  .catch(error => {
    
    
    // 处理错误
    console.error(error);
  });

By configuring responseType to 'text', you can specify that the response type is text, and Axios will return the response data as a string.

3. Process Blob data:

// 引入 Axios
import axios from 'axios';

// 发起 GET 请求,预期响应是 Blob 数据(例如图片)
axios.get('/api/image', {
    
    
  responseType: 'blob', // 指定响应类型为 Blob
})
  .then(response => {
    
    
    // 在响应拦截器中处理 Blob 数据
    const imageUrl = URL.createObjectURL(response.data);
    console.log(imageUrl);

    // 如果需要显示图片,可以将 imageUrl 设置给 img 标签的 src
  })
  .catch(error => {
    
    
    // 处理错误
    console.error(error);
  });

By configuring responseType to 'blob', you can specify the response type as Blob, and Axios will return the response data as a Blob object. In this example, we use URL.createObjectURL to convert the blob data into a URL that can be used to display the image.

These examples show how to handle different types of response data through configuration responseType . Axios provides a wealth of configuration options, allowing you to easily handle various types of response data, and also process responses globally through interceptors.

Interceptors and configuration

Axios' interceptors and configuration options provide a flexible way to insert custom logic at different stages of requests and responses. This allows you to perform additional operations before sending the request or after processing the response. Here is a brief introduction to Axios interceptors and configuration:

1. Request Interceptors:

Request interceptors allow you to manipulate requests before sending them, such as adding request headers, transforming request data, etc.

// 添加请求拦截器
axios.interceptors.request.use(
  config => {
    
    
    // 在请求发送前做些什么
    return config;
  },
  error => {
    
    
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

2. Response Interceptors:

Response interceptors allow you to operate on response data before processing it, such as parsing response data, handling errors uniformly, etc.

// 添加响应拦截器
axios.interceptors.response.use(
  response => {
    
    
    // 对响应数据做些什么
    return response;
  },
  error => {
    
    
    // 对响应错误做些什么
    return Promise.reject(error);
  }
);

3. Config Options:

Axios supports personalized settings through configuration items during requests, such as setting request timeout, customizing request headers, etc.

// 配置项示例
axios({
    
    
  method: 'post',
  url: '/api/data',
  data: {
    
    
    key: 'value'
  },
  headers: {
    
    
    'Content-Type': 'application/json'
  },
  timeout: 5000 // 请求超时时间
})
  .then(response => {
    
    
    console.log(response.data);
  })
  .catch(error => {
    
    
    console.error(error);
  });

4. Interceptor execution sequence:

The execution order of interceptors is based on the order of addition. The interceptor added first will be executed first. Request interceptors are executed from first to last, while response interceptors are executed from last to first.

5. Cancel the interceptor:

You can also cancel the interceptor through the eject method, which needs to pass in the identifier of the interceptor, which is the return value when the interceptor is added.

const requestInterceptorId = axios.interceptors.request.use(/* ... */);
const responseInterceptorId = axios.interceptors.response.use(/* ... */);

// 取消请求拦截器
axios.interceptors.request.eject(requestInterceptorId);

// 取消响应拦截器
axios.interceptors.response.eject(responseInterceptorId);

Through interceptors and configuration items, you can more flexibly control the processing flow of requests and responses. Interceptors provide a clear and maintainable solution for scenarios such as pre-processing before processing requests, handling errors, and unified processing of responses. .

Error handling

In Axios, you can handle various errors that may be encountered in HTTP requests through .catch methods or error handling in response interceptors. Here are some common error handling scenarios:

1. Request error:

Request errors usually occur when the network request fails or the request cannot be sent, such as network unavailability, cross-domain issues, etc.

axios.get('/api/data')
  .then(response => {
    
    
    console.log(response.data);
  })
  .catch(error => {
    
    
    // 请求错误处理
    if (error.response) {
    
    
      // 请求已发出,但服务器返回状态码不在 2xx 范围内
      console.error('Status Code:', error.response.status);
      console.error('Response Data:', error.response.data);
    } else if (error.request) {
    
    
      // 请求已发出,但没有收到响应
      console.error('No Response Received');
    } else {
    
    
      // 在设置请求时触发了错误
      console.error('Request Setup Error:', error.message);
    }
  });

2. Response error:

Response error refers to the server returning an error status code, such as 404 Not Found, 500 Internal Server Error, etc.

axios.get('/api/nonexistent-endpoint')
  .then(response => {
    
    
    console.log(response.data);
  })
  .catch(error => {
    
    
    // 响应错误处理
    console.error('Status Code:', error.response.status);
    console.error('Response Data:', error.response.data);
  });

3. Other errors:

Other errors may include request timeout, canceled request, etc.

axios.get('/api/data', {
    
     timeout: 5000 }) // 设置请求超时时间为 5 秒
  .then(response => {
    
    
    console.log(response.data);
  })
  .catch(error => {
    
    
    // 其他错误处理
    if (axios.isCancel(error)) {
    
    
      // 请求被取消
      console.error('Request Canceled:', error.message);
    } else if (axios.isTimeout(error)) {
    
    
      // 请求超时
      console.error('Request Timeout');
    } else {
    
    
      // 其他错误
      console.error('Other Error:', error.message);
    }
  });

4. Global error handling:

Through interceptors, you can also set up global error handling to capture all request and response errors.

// 添加全局的响应拦截器
axios.interceptors.response.use(
  response => {
    
    
    // 对响应数据做些什么
    return response;
  },
  error => {
    
    
    // 全局响应错误处理
    console.error('Global Response Error:', error.message);
    return Promise.reject(error);
  }
);

By combining the above error handling methods, you can more comprehensively handle various errors that may occur in Axios requests, thereby improving the stability and reliability of your application.

Guess you like

Origin blog.csdn.net/m0_68390957/article/details/134585390