# axios 学习笔记
标签(空格分隔): 数据请求 axios
---
## 1. 下载与安装
+ npm i axios -S
+ import axios from 'axios'
## 2. 使用
+ get请求
```
//参数拼接的写法
axios.get('/index?ID=12345').then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
//参数以对象的方式传入
axios.get('/index'{
params: {
ID: 12345
}
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
```
+ post请求
```
axios.post('/user', { //注意这里和get中传入对象不同,这里直接传入对象,而get中需要传入一个属性为params的对象,要传的参数对象作为params的属性值
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
```
+ 执行多个并发请求
```
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成 acct perms 分别代表两个请求的返回值
}));
```
+ 可以通过向 axios 传递相关配置来创建请求
```
// 发送 POST 请求
axios({
method: 'post',
url: '/user/12345',
data: {
name: 'jack',
age: 18
}
});
// 发送 GET 请求(默认的方法)
axios('/user/12345');
```
+ 配置项
- 可以通过axios.default设置全局默认属性
如配置根路径:axios.default.baseURL = 'http://localhost:8080'
- 也可以自定义实例默认值
```
var instance = axios.create({
baseURL: 'https://api.example.com'
});
//这样就可以通过实例来发送请求了
instance.get('/index')
```
## 3. 拦截器
在请求或响应在被then或catch处理前拦截它们
```
//添加请求拦截器
axios.interceptor.request.use(function (config) {
//在发起请求之前要做什么
return config
},function (error) {
// 请求错误时做什么
return Promise.reject(error)
})
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
```