axios发送get无参请求
axios.get('http://localhost:9999/student/getAllStudent')
.then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
axios发送get有参请求
axios.get('http://localhost:9999/student/getAllStudent',{params:{id:1}})
.then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
axios发送post无参请求
axios.post('http://localhost:9999/student/getAllStudent')
.then(res=>{ //把get无参请求的get改为post即可
console.log(res)
}).catch(err=>{
console.log(err)
})
axios发送post有参请求
axios.post('http://localhost:9999/student/getAllStudent',"name=张三&age=10")
.then(res=>{ //发送post请求携带参数,直接使用"name=张三&age=10"
console.log(res)
}).catch(err=>{
console.log(err)
})
axios发送post有参请求
axios.post('http://localhost:9999/student/findStudentByName',{name:'张三'})
.then(res=>{ //发送post请求携带参数,这种传参方式后台得使用requestBody处理
console.log(res)
}).catch(err=>{
console.log(err)
})
什么情况下会出错呢?
用data传参,后台不用requestbody接收的话,name会为null
axios({
url:''http://localhost:9999/student/findStudentByName',
method:'post',
data:{
name:'张三' //后台不用requestbody接收的话,name会为null
}
}).then(res=>{
console.log(res)
})
axios.all发送并发请求,获取所有学生和指定id学生
axios.all([
axios.get('http://localhost:9999/student/findStudentById'),
axios.get('http://localhost:9999/student/getAllStudent',{params:{id:1}})
]).then(res=>{
console.log(res[0]); //第一种方式使用数组的方式返回,res[0],res[1]返回请求结果
console.log(res[1])
}).catch(err=>{
console.log(err)
})
用axios.spread处理并发请求
axios.all([
axios.get('http://localhost:9999/student/findStudentById'),
axios.get('http://localhost:9999/student/getAllStudent',{params:{id:1}})
]).then(
axios.spread((res1,res2)=>{
console.log(res1) //res1,res2获取俩个请求的结果,只是看起来更高大上
console.log(res2)
})
).catch(err=>{
console.log(err)
})
axios全局配置baseURL和超时
axios.defaults.baseURL='http://localhost:9999/student/student';
axios.defaults.timeout=5000; //5秒超时设置
![](https://i-blog.csdnimg.cn/blog_migrate/256ae6300bb2bd5ca90e37cbd937bcd0.jpeg)