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

8.axios Http网络请求库(1)

一句话总结

Axios 是一个基于 Promise 的 HTTP 客户端,用于浏览器和 Node.js,帮助你轻松发送请求、接收响应。

Axios is a Promise-based HTTP client for the browser and Node.js, making it easy to send requests and handle responses.

📌 Axios 是什么?(What is Axios)

Axios 是一个 轻量级的 HTTP 请求库,支持浏览器和 Node.js 环境。它封装了 XMLHttpRequest(浏览器)和 http 模块(Node.js),让我们用更简单、统一的方式进行网络通信。

✨ 有什么特性?(Features of Axios)
• 支持 Promise API(可用 async/await)
• 自动转换 JSON 数据
• 拦截请求和响应(request/response interceptors)
• 支持请求取消(cancellation)
• 客户端防止 CSRF 攻击(自动设置 XSRF token)
• 可以设置请求超时、响应数据格式等
• 支持上传、下载进度监听

❓ 为什么需要 Axios?(Why use Axios)
• 原生 fetch 写法繁琐、对旧浏览器支持不好
• XMLHttpRequest 太底层,回调多,难维护
• Axios 提供统一接口、丰富功能,更适合现代开发

✅ Axios 的优点(Advantages of Axios)
• 使用简单,语法清晰
• 默认支持 JSON 数据的处理
• 跨平台支持(浏览器和 Node.js)
• 可配置性强,适合项目中进行统一封装
• 社区活跃,文档完善

🔧 可以做什么?(What can you do with Axios)
• 发送 GET / POST / PUT / DELETE 等 HTTP 请求
• 向后端接口提交表单、JSON、文件等数据
• 调用 REST API 接口并处理返回结果
• 构建基于服务端数据的前端应用(如 Vue / React 项目)

🛠️ 怎么使用?(How to use Axios)

  1. 安装(Install)

npm install axios

yarn add axios

  1. 基本用法(Basic Usage)

import axios from ‘axios’;

axios.get(‘https://api.example.com/data’)
.then(response => {
console.log(response.data); // 处理返回数据
})
.catch(error => {
console.error(error); // 处理错误
});

  1. 使用 async/await

async function fetchData() {
try {
const res = await axios.get(‘https://api.example.com/data’);
console.log(res.data);
} catch (err) {
console.error(err);
}
}

  1. 配置请求参数

axios.post(’/api/login’, {
username: ‘test’,
password: ‘123456’
}, {
headers: {
‘Content-Type’: ‘application/json’
},
timeout: 5000
});

  1. 拦截器使用(Interceptors)

axios.interceptors.request.use(config => {
config.headers.Authorization = ‘Bearer your_token’;
return config;
});

axios.interceptors.response.use(
response => response,
error => Promise.reject(error)
);

相关文章:

  • 源码编译 Cas Server 4/5/6/7
  • 无人机军用与民用技术对比分析
  • App使用webview套壳引入h5(三)——解决打包为app后在安卓机可物理返回但是在苹果手机无法测滑返回的问题
  • Uniapp 二维码生成与解析完整教程
  • win32相关(远程线程和远程线程注入)
  • Spring框架学习day7--SpringWeb学习(概念与搭建配置)
  • 深度解析地质灾害风险普查:RS与GIS技术在泥石流、滑坡灾害中的应用,ArcGIS数据管理、空间数据转换、专题地图制作、DEM分析及实战案例分析
  • 实用对比图软件推荐:快速呈现信息差异
  • opencv-4.8.1到 sln
  • Excel数据分析:基础
  • Tensorrt python api 10.11.0笔记
  • 红花UGT鉴定与特征分析-文献精读142
  • 本地部署大模型实战:使用AIStarter一键安装Ollama+OpenWeb教程(含最新版本更新指南)
  • 适用于vue3的大屏数据展示组件库DataV(踩坑版)
  • QQ邮箱发送验证码(Springboot)
  • vue和uniapp聊天页面右侧滚动条自动到底部
  • 第六个微信小程序:教师工具集
  • 负载均衡将https请求转发后端http服务报错:The plain HTTP request was sent to HTTPS port
  • [Zynq] Zynq Linux 环境下 AXI UART Lite 使用方法详解(代码示例)
  • opencv如何在仿射变换后保留完整图像内容并自动裁剪
  • 广东省建设厅网站可以查/友链交易平台源码
  • 紧固件做网站有效果吗/学seo需要学什么专业
  • ps加dw做网站/北京网络营销推广培训哪家好
  • 嘉兴商城网站开发设计/指数基金定投技巧
  • 做婚恋交友类网站/重庆百度快照优化排名
  • 做网站维护有什么要求/专业网站优化外包