时间:2025-05-09 08:52
人气:
作者:admin
Axios简介
Axios是一个基于Promise的HTTP客户端,用于浏览器和Node.js环境。它提供了一个简单、方便的API来处理HTTP请求和响应,并具备多种强大的特性,使其成为现代Web开发中不可或缺的工具。
Axios的用法
1.安装Axios
在Node.js项目中,可以通过npm或yarn安装Axios。在浏览器中,可以直接通过script标签引入Axios的CDN链接。
npm install axios
或者
通过script src="https://unpkg.com/axios/dist/axios.min.js"
2.创建Axios实例
在Node.js中,可以通过new Axios()创建一个新的Axios实例;在浏览器中,可以通过axios.create()创建新的Axios实例。
const axios = require('axios');
const instance = axios.create({
baseURL: 'https://api.example.com',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
3.设置请求参数
通过Axios实例的request方法设置请求参数,如URL、请求方法、请求头等。
const config = {
method: 'get',
url: '/user/12345',
params: {
ID: 12345
}
};
4.发送请求
通过Axios实例的get、post、put、delete方法发送HTTP请求。
instance.get('/user?ID=12345')
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.error(error);
});
5.处理响应
通过Promise的then、catch方法处理HTTP响应。
instance.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.error(error);
});
Axios的创作流程
Axios的创作流程主要包括以下几个步骤:
Axios的优缺点
优点:
缺点:
代码案例
const [type5Response, type0Response, type1Response] = await Promise.all([
// 获取文件夹(type=5)
axios.get(baseurl + `/netdisk-prod-api/out/list?pageNum=1&pageSize=10&type=5&parentId=${categoryId}`),
// 获取图片(type=0)
axios.get(baseurl + `/netdisk-prod-api/out/list?pageNum=1&pageSize=10&type=0&parentId=${categoryId}`),
// 获取视频(type=1)
axios.get(baseurl + `/netdisk-prod-api/out/list?pageNum=1&pageSize=10&type=1&parentId=${categoryId}`)
]);
// 处理文件夹内容
await Promise.all(type5Response.data.rows.map(async (item) => {
const mediaDiv = document.createElement('div');
mediaDiv.className = 'grid-item album';
try {
// 获取文件夹内容
const response = await axios.get(baseurl + `/netdisk-prod-api/out/list?pageNum=1&pageSize=10&parentId=${item.id}`);
const subItems = response.data.rows;
}catch (error) {
console.error('Error processing folder:', error);
}
}));
发送GET请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.error(error);
});
解释:
axios.get:发送GET请求。
'/user?ID=12345':请求的URL和参数。
.then(function (response) {...}):处理成功响应。
.catch(function (error) {...}):处理错误响应。
发送POST请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.error(error);
});
解释:
axios.post:发送POST请求。
'/user':请求的URL。
{firstName: 'Fred', lastName: 'Flintstone'}:请求的数据。
.then(function (response) {...}):处理成功响应。
.catch(function (error) {...}):处理错误响应。
使用拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么,例如添加公共头部信息
config.headers['Authorization'] = 'Bearer token';
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么,例如进行数据加密、解密等
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
解释:
axios.interceptors.request.use:添加请求拦截器。
axios.interceptors.response.use:添加响应拦截器。
在请求拦截器中,可以修改请求的配置,如添加头部信息。
在响应拦截器中,可以修改响应的数据或处理错误。
Axios的使用场景