一、axios是基于promise对ajax的一种封装
二、axios的基本使用
1.使用默认方式发送请求,get
<script src="../axios/axios.min.js"></script>
<script>
axios({
//默认是get请求
url:'http://localhost:9999/student/student/getAllSyudent'
}).then(res>{
console.log(res);
})
2.指定请求方式,get,发送无参请求
<script src="../axios/axios.min.js"></script>
<script>
axios({
url:'http://localhost:9999/student/student/getAllSyudent',
methods:'get'
}).then(res>{
console.log(res);
})
</script>
3.1 get有参请求
<script src="../axios/axios.min.js"></script>
<script>
axios({
url:'http://localhost:9999/student/student/findStudentById?id=1'
}).then(res=>{
console.log(res);
})
</script>
3.2 get有参请求其他形式
<script src="../axios/axios.min.js"></script>
<script>
axios({
url:'http://localhost:9999/student/student/findStudentById',
params:{
id:'1'
}
}).then(res=>{
console.log(res);
})
</script>
4.使用post发送无参请求
<script src="../axios/axios.min.js"></script>
<script>
axios({
url:'http://localhost:9999/student/student/pGet',
methods:'post'
}).then(res>{
console.log(res);
})
</script>
5.使用post发送有参请求
<script src="../axios/axios.min.js"></script>
<script>
axios({
url:'http://localhost:9999/student/student/findStudentByName',
method:'post',
params:{
name:'zs'
}
}).then(res=>{
console.log(res);
})
</script>
后台控制器接收到的name是null,axios使用post携带参数请求默认使用application/json
解决方式一:params属性进行数据的传递
解决方式二:"name=张娜"
解决方式三:服务器端给接收的参数加上@requestBody
三、axios的请求方式
1.使用axios.get方式发送无参请求
<script src="../axios/axios.min.js"></script>
<script>
axios.get('http://localhost:9999/student/student/getAllStudent')
.then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
})
</script>
2.使用axios.get方式发送有参请求
<script src="../axios/axios.min.js"></script>
<script>
axios.get('http://localhost:9999/student/student/findStudentById',
{params:{id:1,name:'zs'}}).then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
})
</script>
3.使用post无参请求
<script src="../axios/axios.min.js"></script>
<script>
axios.post('http://localhost:9999/student/student/pGet').then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
})
</script>
4.使用post有参请求 只修改前端代码
<script src="../axios/axios.min.js"></script>
<script>
axios.post('http://localhost:9999/student/student/findStudentByName',"name=zs&age=10")
.then(res=>{
console.log(res);
});
</script>
多个参数使用&连接
5.使用data传递数据 后台需要将axios自动转换的json数据转换为java对象 需要修改后台代码
<script src="../axios/axios.min.js"></script>
<script>
axios.post('http://localhost:9999/student/student/findStudentByName',{name:'zs'})
.then(res=>{
console.log(res);
});
</script>