返回

Axios 入门指南:掌握前端请求利器

前端

Axios 简介

Axios 是一款基于 Promise 的 HTTP 客户端,适用于浏览器和 Node.js。它具有以下特点:

  • 支持浏览器和 Node.js
  • 支持 Promise
  • 能拦截请求和响应
  • 能转换请求和响应数据
  • 能取消请求
  • 自动转换 JSON 数据

Axios 的使用方法

1. 安装 Axios

在项目中安装 Axios:

npm install axios

2. 导入 Axios

在项目中导入 Axios:

import axios from 'axios';

3. 发起 GET 请求

使用 Axios 发起 GET 请求:

axios.get('https://example.com/api/users')
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.log(error);
  });

4. 发起 POST 请求

使用 Axios 发起 POST 请求:

axios.post('https://example.com/api/users', {
  name: 'John Doe',
  email: 'johndoe@example.com'
})
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.log(error);
  });

5. 发起 PUT 请求

使用 Axios 发起 PUT 请求:

axios.put('https://example.com/api/users/1', {
  name: 'John Doe',
  email: 'johndoe@example.com'
})
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.log(error);
  });

6. 发起 DELETE 请求

使用 Axios 发起 DELETE 请求:

axios.delete('https://example.com/api/users/1')
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.log(error);
  });

7. 设置请求头

使用 Axios 设置请求头:

axios.get('https://example.com/api/users', {
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer <token>'
  }
})
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.log(error);
  });

8. 设置请求参数

使用 Axios 设置请求参数:

axios.get('https://example.com/api/users', {
  params: {
    page: 1,
    limit: 10
  }
})
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.log(error);
  });

9. 设置请求超时时间

使用 Axios 设置请求超时时间:

axios.get('https://example.com/api/users', {
  timeout: 10000
})
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.log(error);
  });

10. 取消请求

使用 Axios 取消请求:

const controller = new AbortController();
const signal = controller.signal;

axios.get('https://example.com/api/users', {
  signal: signal
})
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.log(error);
  });

controller.abort();

结语

Axios 是一款功能强大、使用方便的 HTTP 客户端,深受前端开发者的喜爱。通过本文的介绍,您已经掌握了 Axios 的基本使用方法。希望这些知识能帮助您在开发中更加高效。