axios是一个基于Promise的HTTP客户端,可以用于浏览器和Node.js中。以下是axios的基本使用方法:
1. 安装axios模块:
```
npm install axios
```
2. 引入axios模块:
```javascript
const axios = require('axios');
```
3. 发送GET请求:
```javascript
axios.get('/api/user')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
```
4. 发送POST请求:
```javascript
axios.post('/api/user', { name: 'John', age: 25 })
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
```
5. 设置请求头:
```javascript
axios({
method: 'get',
url: '/api/user',
headers: { 'Authorization': 'Bearer token' }
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
```
6. 设置请求参数:
```javascript
axios({
method: 'get',
url: '/api/user',
params: { id: 1 }
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
```
7. 取消请求:
```javascript
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/api/user', { cancelToken: source.token })
.then(response => {
console.log(response.data);
})
.catch(thrown => {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
// 在需要取消请求的时候调用source.cancel()方法即可取消请求
source.cancel('Operation canceled by the user.');
```
标签:axios,console,log,javascript,js,error,方法,response From: https://www.cnblogs.com/full-stack-linux-new/p/17658304.html