axios 学习笔记
axios请求方法:get、post、put、patch、delete
get:获取数据
post:提交数据(表单提交+文件上传)
put:更新数据(所有数据推送到后端)
patch:更新数据(只将修改的数据推送到后端)
delete:删除数据
axios.get('/data.json',{ params:{ id:12 } }).then((res)=>{ console.log(res) })
axios({ methord: 'get', url: '/data.json', params:{ id:12 } }).then(res=>{ console.log(res) })
//加地址后边 delete?id=12
axios.delete('/delete',config).then()
axios.delete('delete',{ params:{ id: 12 } }).then(res=>{console.log(res)})
//不加地址后边
axios.delete('/delete',{ data:{ id: 12 } }).then(res=>{console.log(res)})
不用别名
axios({ method:'delete', url: '/delete' params:{} }).then(res=>{console.log(res)})
并发请求:同时处理多个请求并统一处理返回值
//axios.all() 参数数据
//axios.spread() 分割不同请求的返回值
axios.all( [ axios.get('/data.json'), axios.get('/city.json') ] ).then( axios.spread((dataRes,cityRes)=>{ console.log(dataRes,cityRes) }) )
axios实例
使用场景:当接口地址多个时候(端口号之前的域名可能是多个时候),并且超时时长不一样时。此时就可以通过axios实例,在axios实例中设置这两种参数,然后通过实例去请求接口。
let instance = axios.create({ baseURL : 'http://localhost:8080', timeout: 1000 })
instance.get('/data.json').then(res => console.log(res))
基本配置参数
参数1、baseURL:请求域名,或者是基本地址(默认配置http://localhost:8080,就像通过axios的get('/data.json')访问时,前面添加了默认的域名。
参数2、timeout:超时时长,默认1000毫秒(超时时长作用:一般它由后端定义,例如:请求一个接口,接口的数据量比较大,需要处理时间比较长,如果超过了这个时间,后端就会返回401,这样做的好处是,一旦请求时间较长,使这个请求不会阻塞后端的内容,减少服务器的压力,它就会及时释放超时的这些内容,超时时长不止后端需要设置,前端也需要设置一下,当超时时,请求就取消了)。
参数3、url:请求路径。
参数4、method:请求方法。
参数5、headers:请求头,可以在请求头里添加一些参数(比如登录时可能需要从请求头里获取token,去鉴权获取登录人信息,此时就需要在这里配置)。
https://img4.sycdn.imooc.com/5fe0a9e60001fb2f05960373.jpg
参数6、params{}:请求参数放置在请求头中。
参数7、data:{}请求参数放置在请球体中。
axios定义配置参数的位置
1、axios全局配置(相当于在import的axios的vue页面中对所有创建的axios进行全局配置)
axios.defaults:表示指向axios库的默认配置,defaults后面就可以.出来配置参数。
axios.defaults.timeout=2000,此时就表示全局配置。
axios.defaults.baseURL='http://localhost:8080'。
2、axios实例配置(相当于局部的)
let instance=axios.create(),如果不传配置参数,如果定义了全局,就是用全局,否则使用默认的。
instance.defaults.timeout=3000,这种方式是创建完实例之后去设置参数。
3、axios请求配置(发送请求时)
instance.get('/data.json',{
timeout:5000
})
参数配置优先级:全局<局部<请求。如上,最终timeout为5000。
拦截器
1 axios.interceptors.request.use(config=>{
2 //在发送请求前做些什么
3 return config
4 },err=>{
5 //在请求错误的时候做些什么
6 return Promis.reject(err)
7 })
1 axios.interceptors.response.use(res=>{
2 //请求成功对响应数据做处理
3 return res
4 },err=>{
5 //响应错误做些什么
6 return Promise.reject(err)
7 })
实例 登录状态 token
1 //开发的时候一般是给实例添加拦截器,给全局添加会造成全局污染 2 3 //需要登录的接口 4 let instance = axiios.create({}) 5 instance.interceptors.request.use(config=>{ 6 config.headers.token = '' 7 return config 8 }) 9 10 //不需要登录的接口,另外创建一个实例 11 let newInstance = axios.create({})
//移动端开发
1 let instance_phone = axiios.create({}) 2 //请求等待样式 3 instance_phone.interceptors.request.use(config=>{ 4 $('#modal').show() 5 return config 6 }) 7 //返回响应样式 8 instance_phone.interceptors.response.use(res=>{ 9 $('#modal').show().hide() 10 return res 11 })