当前位置: 首页 > 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://chondral.jopebe.cn
http://brail.jopebe.cn
http://chloramine.jopebe.cn
http://bulldyke.jopebe.cn
http://carritch.jopebe.cn
http://abnaki.jopebe.cn
http://buggy.jopebe.cn
http://astrologist.jopebe.cn
http://carpathian.jopebe.cn
http://aroint.jopebe.cn
http://aequorin.jopebe.cn
http://alarmist.jopebe.cn
http://bughunter.jopebe.cn
http://arrect.jopebe.cn
http://aerofoil.jopebe.cn
http://antecessor.jopebe.cn
http://astonied.jopebe.cn
http://aau.jopebe.cn
http://basan.jopebe.cn
http://arista.jopebe.cn
http://breeching.jopebe.cn
http://austral.jopebe.cn
http://brighish.jopebe.cn
http://animosity.jopebe.cn
http://cacodorous.jopebe.cn
http://astrometry.jopebe.cn
http://altometer.jopebe.cn
http://anyway.jopebe.cn
http://anarthrous.jopebe.cn
http://activise.jopebe.cn
http://www.dtcms.com/a/281296.html

相关文章:

  • 映美打印机-URL页面打印
  • Spring MVC 执行流程详解:一次请求经历了什么?
  • 微信小程序:在ios中border边框显示不全
  • XCTF-repeater三链破盾:PIE泄露+ROP桥接+Shellcode执行的艺术
  • PyTorch 数据加载实战:从 CSV 到图像的全流程解析
  • 股指期货主连和次主连的区别是什么?
  • 游戏加速器核心技术:动态超发
  • Linux 文件系统实现层详解:原理、结构与驱动衔接
  • 人类气道黏膜下腺类器官:解析呼吸炎症与感染的新平台
  • Sharding-JDBC 分布式事务实战指南:XA/Seata 方案解析(三)
  • (3)从零开发 Chrome 插件:网页图片的批量下载
  • Google EMM是什么?
  • Git Idea 冲突解决
  • GitHub Pages无法访问以点号.开头的目录
  • 【实时Linux实战系列】实时数据流的网络传输
  • 百度移动开发面经合集
  • 【matlab】三维路面谱生成代码
  • Altium Designer 25 安装与配置完整教程
  • 【高并发服务器】多路复用的总结 eventfd timerfd
  • 2.3 数组与字符串
  • Flutter 股票图实现分析与解决方案
  • 深入理解高性能字节池 bytebufferpool
  • 1.easypan-登录注册
  • AbMole小课堂 | Angiotensin II(血管紧张素Ⅱ)在心血管研究中的多元应用
  • 基于51单片机和16X16点阵屏、矩阵按键的小游戏《俄罗斯方块》
  • 清理C盘--办法
  • python的形成性考核管理系统
  • 学习笔记(37):构建一个房价预测模型,并通过可视化全面评估模型效果
  • Java 异常处理详解:从基础语法到最佳实践,打造健壮的 Java 应用
  • Linux进程信号--0、序章