利用axios向后端传递数据
1.利用data传递参数,后端需要用实体类接受,参数在请求体里面,因此只能用post请求
前端代码
axios({
url:"/book/user/login",
method:"post",
contentType:"application/json",
data:{
username:this.ruleForm.username,
password:this.ruleForm.pass
}
}).then(function (response) {
alert(response.data);
});
后端代码,需要用@RequestBody 注释
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/login")
@ResponseBody
public String login(@RequestBody User user) {
System.out.println(user);
return "success";
}
}
注意事项,使用这种方法需要导入jackson依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
2.利用params传递参数
axios({
url:"/book/user/login",
method:"post",
contentType:"application/json",
params:{
username:this.ruleForm.username,
password:this.ruleForm.pass
}
}).then(function (response) {
alert(response.data);
});
后端用字符串参数接受
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/login")
@ResponseBody
public String login(String username,String password) {
System.out.println(username+password);
return "success";
}
}
3.get请求和只用用params传参,用法和post差别不大