返回
**Axios学习笔记-全网最全的Axios教学指南**
前端
2023-10-04 10:12:24
1. Axios 是什么?
Axios 是一个基于 Promise 的 HTTP 库,可以轻松地发送异步 HTTP 请求。它在前端开发中非常受欢迎,React 和 Vue 都推荐使用它来发送 Ajax 请求。
2. Axios 的特点
- 基于 Promise,可以轻松地处理异步请求
- 支持多种请求方法,如 GET、POST、PUT、DELETE 等
- 可以发送 JSON 数据
- 可以设置请求头和请求超时时间
- 可以拦截请求和响应
- 支持跨域请求
3. Axios 的安装
可以通过 npm 或 yarn 来安装 Axios:
npm install axios
yarn add axios
安装完成后,可以在项目中导入 Axios:
import axios from 'axios';
4. Axios 的基本用法
发送一个 GET 请求:
axios.get('https://example.com/api/users')
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
发送一个 POST 请求:
axios.post('https://example.com/api/users', {
name: 'John Doe',
email: 'johndoe@example.com',
})
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
5. Axios 的高级用法
- 设置请求头:
axios.get('https://example.com/api/users', {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer <token>',
},
})
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
- 设置请求超时时间:
axios.get('https://example.com/api/users', {
timeout: 10000,
})
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
- 拦截请求和响应:
axios.interceptors.request.use((config) => {
// 在发送请求之前做一些事情
return config;
});
axios.interceptors.response.use((response) => {
// 在收到响应之后做一些事情
return response;
});
- 支持跨域请求:
axios.get('https://example.com/api/users', {
withCredentials: true,
})
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
6. Axios 的常见示例
- 获取用户列表:
axios.get('https://example.com/api/users')
.then((response) => {
const users = response.data;
// 使用用户列表做一些事情
})
.catch((error) => {
console.error(error);
});
- 创建一个新用户:
axios.post('https://example.com/api/users', {
name: 'John Doe',
email: 'johndoe@example.com',
})
.then((response) => {
const user = response.data;
// 使用新用户做一些事情
})
.catch((error) => {
console.error(error);
});
- 更新一个用户:
axios.put('https://example.com/api/users/1', {
name: 'Jane Doe',
email: 'janedoe@example.com',
})
.then((response) => {
const user = response.data;
// 使用更新后的用户做一些事情
})
.catch((error) => {
console.error(error);
});
- 删除一个用户:
axios.delete('https://example.com/api/users/1')
.then((response) => {
// 用户已删除
})
.catch((error) => {
console.error(error);
});