axios简写get和post请求
使用axios.get方式发送无参请求
<script>
axios.get('http://localhost:8080/student/getAllStudent').then(res=>{
console.log(res.data);
}).catch(err=>{
console.log(err);
});
</script>
使用axios.get方式发送有参请求
<script>
axios.get('http://localhost:8080/student/getStudentById',{params:{id:1,name:'zhangsan'}}).then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
});
</script>
使用axios.post方式发送无参请求
<script>
axios.post('http://localhost:8080/student/getAllStudent').then(res=>{
console.log(res.data);
}).catch(err=>{
console.log(err);
});
</script>
使用axios.post方式发送有参请求【方式一】(这种方式后端controller的接口不需要加@RequestBody注解)
<script>
axios.post('http://localhost:8080/getUser',"id=1&age=20&name=张三").then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
});
</script>
后端:(前端请求的参数名称必须与接口入参一致)
@CrossOrigin//允许跨域
@PostMapping("getUser")
public String getUser(int id,String age,String name){
System.out.println(id);
System.out.println(age);
System.out.println(name);
return "123";
}
使用axios.post方式发送有参请求【方式二】(使用data传递数据,后端需要将axios自动转换的json字符串转换为java对象,方法上添加@RequestBody)
<script>
queryUser:function(){
axios.post('http://localhost:8080/getUser',{id:this.user.id,name:this.user.name,age:this.user.age}).then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
});
</script>
后端:
@CrossOrigin
@PostMapping("getUser")
public String getUser(@RequestBody User user){
System.out.println(user.getId());
System.out.println(user.getName());
System.out.println(user.getAge());
return "123";
}
携带header
<script>
let formData = JSON.stringify(this.obj);
queryUser:function(){
axios.post('http://localhost:8080/getUser',formData,{headers:{'Content-Type':'application/json'}}).then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
});
</script>

浙公网安备 33010602011771号