安装:npm install axios --save
基本使用:
1
2
3
4
axios({
url:' ',
methods:' '//可以在method上指定是什么请求,默认是get请求
}).then(result => { })
发送并发请求 axios.all()
eg:axiso.all([axios(), axios()]).then()
其中axios.all()
返回的结果是一个数组,可以使用axios.spread
将数组[res1, res2]
展开为res1,res2
,即.then(axios.spread((res1, res2) => { } ))
创建axios实例:
1
2
3
4
5
6
const instance1 = axios.create({
baseURL:'....',
timeout:...,
...
})
instance1({url:'...'}).then()
封装axios
1
2
3
4
5
6
7
8
9
10
11
12
export function request(config){
const instance = axios.create({ //创建axios实例
baseURL:'...',
timeout:...,
})
return instance(config) //发送真正的网络请求
}
//然后在所需地方使用:
request({
url:'...'
}).then().catch()
axios拦截器
1
2
3
4
5
//请求拦截
instance.interceptors.request.use(config =>{
...
return config
}, err => { ... })
请求拦截的作用:
- config中的一些信息不符合服务器时修改
- 每次发送网络请求时,都希望在界面中显示一个请求图标
- 某些网络请求(比如登录(token)),必须携带一些特殊信息
1
2
3
4
5
//响应拦截
instance.interceptors.response.use(config =>{
...
return res.data
}, err => { ... })