axios入门

1.axios

axios({
    url:'https://...',
    methods:'get',
    params:{
        id: 'wdnmd'
    }
}).then(res=>{
    console.log(res);
})
//methods可以不写默认get
//不推荐使用params,本质是直接在url后加上“?name=1”,安全性堪忧

2.axios简写方式

axios.get('https://...',{params{id:1,name:"张三"}}).then(res=>{
    console.log(res);
}).catch(err=>{
    console.log(err);
})

//建议使用一下方法
axios.post('http://...',"name=张三&age=10").then(res=>{
    console.log(res)
})

3.axios并发请求

axios.all([
    axios.get('http://...'),
    axios.get('http://...',{params:{id:1}})
]).then(res=>{ //请求响应成功是一个数组
    console.log(res[0]);   
    console.log("------");
    console.log(res[1]);
}).catch(err=>{
    console.log(err);
})
//使用spread
axios.all([
    axios.get('http://...'),
    axios.get('http://...',{params:{id:1}})
]).then(
	axios.spread((res1,res2)=>{
		console.log(res1);
 		console.log(res2);
    })
).catch(err=>{
	console.log(err);
})

4.axios的全局配置

axios.defaults.baseURL='http://...'; //配置全局属性
axios.defaults.timeout=5000;

axios.get('getAllStudents').then(res=>{ //在全局配置的基础上去网络请求
    console.log(res);
});
axios.post('pGet').then(res=>{
    console.log(res);
}).catch(err=>{
    console.log(err);
})

5.axios实例

let newVar = axios.create({
    baseURL:'http://...',
    timeout:5000
}); //创建axios的实例
newVar({
    url:'getAllStudent'
}).then(res=>{
    console.log(res)
})

6.axios拦截器

两种拦截器:请求方向的拦截(成功、失败)和响应方向的拦截(成功、失败)

拦截器的作用

  • 用于我们在网络请求的时候发起请求或者响应时对操作进行相应的处理

  • 发起请求时可以添加网页加载动画

  • 响应时可以进行相应数据处理

//请求方向拦截器
axios.interceptors.request.use(config=>{
	console.log("进入请求拦截器");
	console.log(config);
	return config; //放行请求
},err=>{
	console.log("请求失败");
	console.log(err);
});

axios.get("http://...").then(res=>{
	console.log(res)	
})
//响应方向拦截器
axios.interceptors.response.use(config=>{
	console.log("进入响应拦截器");
	return config;
	return config.data;
},err=>{
	console.log("请求失败");
	console.log(err);
});

axios.get("http://...").then(res=>{
	console.log(res)	
})

7.axios在Vue的模块封装

安装:npm install axios --save

posted @ 2021-02-03 11:15  巴伐利亚药水哥  阅读(24)  评论(0)    收藏  举报