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

Axios 完整功能介绍和完整示例演示

Axios 是一个基于 Promise 的现代化 HTTP 客户端库,用于浏览器和 Node.js 环境。它提供了简洁的 API 和强大的功能,是前端开发中最常用的网络请求工具之一。


核心功能

  1. 浏览器 & Node.js 双平台支持
    • 浏览器中使用 XMLHttpRequest
    • Node.js 中使用 http 模块
  2. Promise API
    所有请求返回 Promise 对象,支持 async/await
  3. 请求/响应拦截器
    全局拦截请求和响应
  4. 请求取消
    使用 AbortController 取消请求
  5. 自动转换数据
    自动转换 JSON 数据,支持请求/响应数据转换
  6. 客户端 XSRF 防护
    自动添加 CSRF 令牌
  7. 并发请求
    提供 axios.all()axios.spread()
  8. 进度监控
    支持上传/下载进度跟踪
  9. 配置默认值
    全局配置 baseURL、headers 等

完整示例演示

1. 基础安装
npm install axios
# 或
yarn add axios
2. 发起请求
import axios from 'axios';// GET 请求
axios.get('https://jsonplaceholder.typicode.com/posts/1').then(response => console.log(response.data)).catch(error => console.error(error));// POST 请求
axios.post('https://jsonplaceholder.typicode.com/posts', {title: 'foo',body: 'bar',userId: 1
})
.then(response => console.log(response.data));
3. 并发请求
const getUser = () => axios.get('https://jsonplaceholder.typicode.com/users/1');
const getPosts = () => axios.get('https://jsonplaceholder.typicode.com/posts?userId=1');Promise.all([getUser(), getPosts()]).then(([userResponse, postsResponse]) => {console.log('User:', userResponse.data);console.log('Posts:', postsResponse.data);});
4. 创建实例 & 全局配置
const api = axios.create({baseURL: 'https://api.example.com',timeout: 5000,headers: {'X-Custom-Header': 'foobar'}
});api.get('/data'); // 实际请求 https://api.example.com/data
5. 拦截器 (身份认证示例)
// 请求拦截器
axios.interceptors.request.use(config => {config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;return config;
});// 响应拦截器
axios.interceptors.response.use(response => response,error => {if (error.response.status === 401) {alert('Session expired!');window.location = '/login';}return Promise.reject(error);}
);
6. 取消请求
const controller = new AbortController();axios.get('https://jsonplaceholder.typicode.com/posts', {signal: controller.signal
})
.catch(err => {if (axios.isCancel(err)) {console.log('Request canceled');}
});// 取消请求
controller.abort();
7. 文件上传 & 进度跟踪
<input type="file" id="fileInput">
document.getElementById('fileInput').addEventListener('change', (e) => {const file = e.target.files[0];const formData = new FormData();formData.append('file', file);axios.post('https://api.example.com/upload', formData, {headers: {'Content-Type': 'multipart/form-data'},onUploadProgress: progressEvent => {const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);console.log(`Upload: ${percent}%`);}});
});
8. 错误处理
axios.get('https://invalid-url.example.com').catch(error => {if (error.response) {// 服务器返回 4xx/5xx 响应console.log('Server Error:', error.response.status);} else if (error.request) {// 请求已发送但无响应console.log('Network Error:', error.message);} else {// 请求配置错误console.log('Config Error:', error.message);}});
9. 自定义实例默认值
// 设置全局默认值
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Accept'] = 'application/json';// 实例级覆盖
const instance = axios.create({baseURL: 'https://api.special.com'
});
10. XSRF 防护
// 设置 Cookie 名称和 Header 名称
axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = 'X-CSRFToken';

完整项目示例

// api.js
import axios from 'axios';const api = axios.create({baseURL: 'https://jsonplaceholder.typicode.com',timeout: 10000
});// 请求拦截器
api.interceptors.request.use(config => {console.log(`Sending ${config.method} request to ${config.url}`);return config;
});// 响应拦截器
api.interceptors.response.use(response => {console.log('Received response:', response.status);return response;},error => {console.error('API Error:', error.message);return Promise.reject(error);}
);export const fetchPosts = () => api.get('/posts');
export const createPost = data => api.post('/posts', data);
export const deletePost = id => api.delete(`/posts/${id}`);
// App.js
import { fetchPosts, createPost } from './api';async function main() {try {// 获取数据const posts = await fetchPosts();console.log('Fetched posts:', posts.data.slice(0, 3));// 创建新数据const newPost = await createPost({title: 'Axios Guide',body: 'Complete tutorial for Axios',userId: 1});console.log('Created post:', newPost.data);} catch (error) {console.error('Main error:', error);}
}main();

常见场景解决方案

  1. 处理不同内容类型

    // 发送 URL 编码数据
    axios.post('/submit', 'key1=value1&key2=value2', {headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    });// 发送纯文本
    axios.post('/log', 'Raw text data', {headers: {'Content-Type': 'text/plain'}
    });
    
  2. 处理二进制数据

    axios.get('https://example.com/image.png', {responseType: 'arraybuffer'
    }).then(response => {const buffer = Buffer.from(response.data, 'binary');fs.writeFileSync('image.png', buffer);
    });
    
  3. 自定义序列化

    axios.post('/data', { special: '@value' }, {transformRequest: [(data) => {return JSON.stringify(data).replace('@', '');}]
    });
    

Axios 通过其简洁的 API 设计和丰富的功能,极大简化了 HTTP 请求的处理流程。无论是简单的 GET 请求还是复杂的文件上传场景,都能提供优雅的解决方案,是现代化前端开发不可或缺的工具。

http://www.xdnf.cn/news/1127287.html

相关文章:

  • OSPFv3中LSA参数
  • 【Luogu】每日一题——Day3. P6392 中意 (数学 取模)
  • 【深度学习优化算法】06:动量法
  • Sentinel热点参数限流完整示例实现
  • 高温车间(60℃+)如何选高温/宽温边缘网关设备?
  • 如何把手机ip地址切换到外省
  • Datawhale 25年7月组队学习coze-ai-assistant Task1学习笔记:动手实践第一个AI Agent—英伦生活口语陪练精灵
  • 学习C++、QT---26(QT中实现记事本项目实现文件路径的提示、现在我们来学习一下C++类模板、记事本的行高亮的操作的讲解)
  • etcd自动压缩清理
  • QT——QComboBox组合框控件
  • Flink实战项目——城市交通实时监控平台
  • 函数柯里化详解
  • Luban配置教程
  • 如何在simulink中怎么获取足端轨迹代码解释?
  • 【卡尔曼滤波第六期】集合变换卡尔曼滤波 ETKF
  • PyTorch笔记7----------计算机视觉基础
  • SSM框架学习DI入门——day2
  • flutter弹窗:fluttertoast
  • AI-Compass LLM训练框架生态:整合ms-swift、Unsloth、Megatron-LM等核心框架,涵盖全参数/PEFT训练与分布式优化
  • 开通保存图片权限
  • 专业文档搜索工具,快速定位文本内容
  • 简单2步配置CadenceSkill开发编辑器,支持关键字高亮
  • 《大数据技术原理与应用》实验报告四 MapReduce初级编程实践
  • excel 通过openpyxl表格下载和插入图片
  • Linux的用户和用户组与权限解析、环境变量说明与配置、sudo配置解析和使用
  • Linux系统下 挂载exfat文件系统U盘
  • 【C语言进阶】字符函数和字符串函数的内部原理
  • 解锁Redis:从安装到配置的全攻略
  • sqli-labs靶场通关笔记:第18-19关 HTTP头部注入
  • 阿里云 Kubernetes 的 kubectl 配置