axios的用法和例子
时间: 2023-11-30 22:35:14 浏览: 28
axios是一个基于Promise的HTTP客户端,可以用于浏览器和Node.js平台。它是一个简单易用的库,可以发送HTTP请求并处理响应。
使用axios发送请求的基本用法如下:
```javascript
// 发送GET请求
axios.get('/api/data')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 发送POST请求
axios.post('/api/data', {
name: 'John Doe',
email: 'john.doe@example.com'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
```
上述代码中,使用axios发送了GET和POST请求,并在then方法中处理了响应数据。如果请求失败,会在catch方法中打印错误信息。
另外,axios还提供了许多其他功能,如设置请求头、发送FormData数据、取消请求等。以下是一些使用axios的例子:
1. 设置请求头
```javascript
axios.get('/api/data', {
headers: {
'Authorization': 'Bearer ' + token
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
```
2. 发送FormData数据
```javascript
var formData = new FormData();
formData.append('name', 'John Doe');
formData.append('email', 'john.doe@example.com');
axios.post('/api/data', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
```
3. 取消请求
```javascript
var source = axios.CancelToken.source();
axios.get('/api/data', {
cancelToken: source.token
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
if (axios.isCancel(error)) {
console.log('请求已取消:', error.message);
} else {
console.log(error);
}
});
// 取消请求
setTimeout(function () {
source.cancel('请求已被取消');
}, 1000);
```
上述代码中,使用CancelToken可以取消请求,可以在setTimeout方法中调用source.cancel方法来取消请求。同时,在catch方法中,使用axios.isCancel方法判断请求是否已被取消。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)