当前位置: 首页 > news >正文

前端学习教程-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=123name: '张三'}}).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 => {// 添加 tokenconfig.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);
});
http://www.hskmm.com/?act=detail&tid=24484

相关文章:

  • 『回忆录』返校前夜 230102
  • 断更
  • 前端学习教程-环境配置
  • TypeScript - Ref
  • 20251004 qmd 弱化规约(未完成)
  • 深入解析:人工智能专业术语详解(C)
  • 2025.10.4模拟赛
  • 黄金替罪羊
  • P5301 [GXOI/GZOI2019] 宝牌一大堆
  • 10.4 2025多校冲刺CSP模拟赛2 改题记录
  • 【比赛记录】2025CSP-S模拟赛58
  • 回忆有感
  • 框架高效的系统的演进如何塑造人工智能的深层语义分析能力
  • 『回忆录』高二上第一次月考——压力下的崛起,意料外的突破
  • AutoCAD 2025安装包下载 CAD免费下载 永久免费激活 附详细安装教程
  • 微分和积分的区别
  • 202509_QQ_secret
  • 4 对拍杂谈
  • Matlab R2024b下载及详细安装教程,附永久免费Matlab安装包
  • Luogu P1966
  • 题解:P14036 [PAIO 2025] Rooks
  • 2025/8/26
  • 27 考研初试时间大约是什么时候?
  • 数据结构 - 跳表 Skip List
  • 06. 定时器
  • NOIP之前的复健记录
  • Linux 命令行安装达梦数据库
  • Google开源Tunix:JAX生态的LLM微调方案来了
  • 实用指南:Matlab通过GUI实现点云的快速全局配准(FGR)
  • 『OI 回忆录』停课有感