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>

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM