前端学习教程-Axios

Axios 是一个基于 Promise 的流行的 HTTP 客户端,用于浏览器和 Node.js 环境,支持 Promise API、拦截请求和响应、转换请求数据和响应数据等功能。

一、安装 Axios

  1. 使用 npm 或 yarn 安装(适用于 Vue/React 等项目):

    npm install axios --save
    # 或
    yarn add axios
    
  2. 使用 CDN 引入(适用于原生 HTML 项目):

    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    

二、基本使用方法

1. 发送 GET 请求

用于从服务器获取数据,可通过 URL 参数传递数据。

// 引入 Axios(模块化项目中)
import axios from 'axios';

// 发送 GET 请求
axios.get('https://api.example.com/users')
  .then(response => {
    console.log('请求成功:', response.data); // 服务器返回的数据
  })
  .catch(error => {
    console.log('请求失败:', error);
  });

// 带参数的 GET 请求
axios.get('https://api.example.com/users', {
    params: {
      id: 123, // 会自动拼接到 URL:?id=123
      name: '张三'
    }
  })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });
2. 发送 POST 请求

用于向服务器提交数据(如表单提交、创建资源),数据放在请求体中。

// 发送 POST 请求
axios.post('https://api.example.com/users', {
    name: '张三',
    age: 20,
    email: 'zhangsan@example.com'
  })
  .then(response => {
    console.log('创建成功:', response.data);
  })
  .catch(error => {
    console.log('创建失败:', error);
  });
3. 其他请求方法

Axios 支持所有 HTTP 方法:getpostput(更新资源)、delete(删除资源)、patch(部分更新)等,用法类似:

运行

// PUT 请求(全量更新)
axios.put('https://api.example.com/users/123', { name: '李四' })
  .then(response => console.log(response))
  .catch(error => console.log(error));

// DELETE 请求
axios.delete('https://api.example.com/users/123')
  .then(response => console.log(response))
  .catch(error => console.log(error));

三、Axios 配置

可以通过配置简化重复的请求参数(如基础 URL、请求头、超时时间等)。

1. 全局配置

设置所有请求的默认配置:

axios.defaults.baseURL = 'https://api.example.com'; // 基础 URL
axios.defaults.headers.common['Authorization'] = 'Bearer token123'; // 全局请求头
axios.defaults.headers.post['Content-Type'] = 'application/json'; // POST 请求头
axios.defaults.timeout = 5000; // 超时时间(毫秒)
2. 实例配置

创建 Axios 实例,单独配置(适用于多服务器请求场景):

// 创建实例
const instance = axios.create({
  baseURL: 'https://api.another-example.com',
  timeout: 8000,
  headers: { 'X-Custom-Header': 'foobar' }
});

// 使用实例发送请求
instance.get('/data')
  .then(response => console.log(response));

四、拦截器

拦截器用于在请求发送前或响应返回后统一处理(如添加 token、处理错误)。

1. 请求拦截器

在请求发送前执行(如添加认证 token):

// 添加请求拦截器
axios.interceptors.request.use(
  config => {
    // 请求发送前的处理(如添加 token)
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config; // 必须返回 config
  },
  error => {
    // 请求错误时的处理
    return Promise.reject(error);
  }
);
2. 响应拦截器

在响应返回后执行(如统一处理错误):

// 添加响应拦截器
axios.interceptors.response.use(
  response => {
    // 响应成功时的处理(只返回数据部分)
    return response.data;
  },
  error => {
    // 响应错误时的处理(如 token 过期)
    if (error.response && error.response.status === 401) {
      // 跳转到登录页
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

五、错误处理

详细处理请求中的各种错误(网络错误、服务器错误等):

axios.get('/data')
  .then(data => console.log(data))
  .catch(error => {
    if (error.response) {
      // 服务器响应了但状态码不是 2xx(如 404、500)
      console.log('状态码:', error.response.status);
      console.log('响应数据:', error.response.data);
    } else if (error.request) {
      // 请求已发送但无响应(如网络错误)
      console.log('无响应:', error.request);
    } else {
      // 其他错误
      console.log('错误信息:', error.message);
    }
  });

六、并发请求

同时发送多个请求,等待所有请求完成后处理:

// 并发请求
axios.all([
  axios.get('/users'),
  axios.get('/posts')
])
.then(axios.spread((usersResponse, postsResponse) => {
  // 两个请求都完成后执行
  console.log('用户数据:', usersResponse.data);
  console.log('文章数据:', postsResponse.data);
}))
.catch(error => {
  console.log('请求失败:', error);
});

七、在 Vue/React 中使用

在框架中通常会封装 Axios 作为请求工具,例如在 Vue 中:

// src/utils/request.js
import axios from 'axios';

const request = axios.create({
  baseURL: '/api', // 基础路径(配合代理解决跨域)
  timeout: 5000
});

// 请求拦截器
request.interceptors.request.use(config => {
  // 添加 token
  config.headers.token = localStorage.getItem('token');
  return config;
});

// 响应拦截器
request.interceptors.response.use(
  res => res.data,
  err => Promise.reject(err)
);

export default request;

在组件中使用:

import request from '@/utils/request';

request.get('/users').then(data => {
  console.log(data);
});
posted @ 2025-10-04 22:10  碧水云天4  阅读(7)  评论(0)    收藏  举报