知识点参考:https://blog.youkuaiyun.com/justry_deng/article/details/80972817/
今天在做一个post提交数据时,发现后台接收到的数据总为null,
- 这是vue前端代码
submitForm(formName) {
this.ruleForm.pic='/img/singerPic/666.jpg';
const _this=this;
this.$refs[formName].validate((valid) => {
if (valid) {
axios.post('http://localhost:8181/singer/addsinger',this.ruleForm).then(function (resp){
if (resp.data!=null){
_this.$message({
message: '新增成功',
type: 'success'
});
}
else {
console.log(resp)
}
})
} else {
console.log('error submit!!');
return false;
}
});
}
- 这是springboot后端
@PostMapping("/addsinger")
public Singer addsinger(Singer singer){
System.out.println(singer);
// singerService.save(singer);
return singer;
}
- 接收到的数据
刚开始并不知道为什么提交了数据为什么后台还是接收不到,起初我把方向转向了前端,是不是前端在获取表单的数据时并没有获取到表单的数据,所以控制台输出一下发现是有数据的。
this.$refs[formName].validate((valid) => {
if (valid) {
console.log(this.ruleForm)
}
});
前端有数据,后端接收为null,那么就是后端的问题,在网上查了资料发现有可能是没加@RequestBody的原因:
@PostMapping("/addsinger")
public Singer addsinger(@RequestBody Singer singer){
System.out.println(singer);
// singerService.save(singer);
return singer;
}
在方法体上加上@RequestBody就可以解决问题了,关于@RequestBody的具体知识请参考:https://blog.youkuaiyun.com/justry_deng/article/details/80972817/