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)

);

相关推荐
光影少年2 小时前
RN与Flutter架构区别
前端·flutter·react native·react.js·架构·node.js
梅孔立1 天前
Codex 完整教程(Node.js安装 + npm安装Codex + DeepSeek配置 + 快捷键 + 设置)
前端·npm·node.js
晚风醉蝶1 天前
webpack 模块提取
前端·webpack·node.js·ast·逆向分析
YIAN2 天前
从 SSE 流式到结构化输出:LangChain 三大 OutputParser 与 ToolCall 方案全实战
前端·langchain·node.js
濮水大叔2 天前
Cabloy全栈框架的两个SSR入口:Vona集成式SSR vs Zova独立式SSR
typescript·node.js·全栈
怕浪猫2 天前
DeepSeek Harness 系列图解
面试·前端框架·node.js
百万蹄蹄向前冲2 天前
双端同步!云服务器装最新Node.js v26.10全过程追踪
服务器·人工智能·node.js
前端snow2 天前
ai agent--- 后端概念补充:Docker Compose、ElasticSearch、IK、BM25等
node.js
EdgeEcho2 天前
Node 里那个"只解第一帧"的坑,我用 172 行代码绕过去了
node.js
光影少年2 天前
Redis + Node 如何支撑百万级并发
redis·后端·node.js