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>

后端:(前端请求的参数名称必须与接口入参一致)

1
2
3
4
5
6
7
8
@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>

  

后端:

1
2
3
4
5
6
7
8
@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>

  

  

posted @   iTao0128  阅读(1747)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示