VUE使用axios的post方式发送数据, 出现数据丢失问题
问题描述:
- 请求头数据
- 后台接收到的数据
- Vue代码
this.commentReply = {
id: this.uuid,
javaId: java.id,
comment: this.value.toString(),
replier: '',
commentator: this.username.toString(),
avatar: '#f0000',
createTime: moment().fromNow()
}
this.comments.push(this.commentReply);
saveComment () {
console.log(this.commentReply)
this.$axios.post(this.url.save, {commentReply: this.commentReply}).then((res) => {
if (res.success) {
this.loadData()
console.log('评论成功')
}
})
},
- 后台代码
@RequestMapping(value = "/saveComment", method = RequestMethod.POST)
public Result<?> saveComment(@RequestBody CommentReply commentReply){
boolean ok = this.replyService.saveComment(commentReply);
log.info("..........要保存的评论" + commentReply.toString());
Result<String> result = new Result<>();
if(ok){
result.setSuccess(true);
result.setMessage("更新成功");
return result;
}
result.setSuccess(false);
result.setMessage("更新失败!");
return result;
}
答
后台
saveComment(@RequestBody CommentReply commentReply);
前台
this.$axios.post(this.url.save, {commentReply: this.commentReply}).then((res)
问题我自己后来解决了:
- 将前端发送数据的方法参数改为 > this.$axios.post(this.url.save, this.commentReply).then((res)... 然后就好了, 尽管之前那种写法没有报错,但是后台接收到的数据都是null值. 根据我的经验: 如果是传递非Json类型数据,比如String或Integer类型的可以用大括号囊括变量名和值,示例{id: '123'} 如果是Json对象类型,直接$axios.post(url, object名), 当然一定要和后台的requestBody或者requestParameter中的变量名一致
答
id不一样,明显不是vue发送的请求,另外,this.commentReply 最好不要用全局变量