Postman中POST请求正常,React Axios调用Spring Boot后端报500错误
问题描述
- React控制台报错:
Failed to load resource: the server responded with a status of 500 (),请求接口为http://localhost:8080/api/review-add - Spring Boot后端报错:
not-null property references a null or transient value : com.reactspringboot.bookclubbackend.entity.Review.account - 用Postman发送同结构JSON的POST请求可正常写入数据库,数据库中id为1的Forum和Account实体已存在
核心问题
React的changeHandler函数中,setReview({comment: event.target.value})直接替换了整个state对象,导致初始state里的account、forum、starRating等属性全部丢失,后端接收的Review对象缺少必填的关联实体,触发非空约束报错。
完整解决方案
一、React前端修复
1. 修复状态更新逻辑
修改changeHandler,使用展开运算符保留原有state的其他属性,仅更新comment字段:
function changeHandler(event) { setReview(prevState => ({ ...prevState, comment: event.target.value })); }
2. 完善提交逻辑(可选)
添加请求回调,方便调试和用户反馈:
function submit(event) { event.preventDefault(); axios.post(postURL, review) .then(response => { console.log("评论提交成功", response.data); // 提交成功后清空评论框 setReview(prevState => ({ ...prevState, comment: "" })); }) .catch(error => { console.error("提交失败", error); }); }
3. 修正表单输入的className拼写错误
原代码中className="form=control"为拼写错误,改为:
<input placeholder="Comment here" name="comment" className="form-control" value={review.comment} onChange={changeHandler}/>
二、Spring Boot后端优化(可选但推荐)
1. 修复GetMapping参数错误
getReviewsByForumId方法同时使用@RequestBody和@PathVariable属于错误用法,@GetMapping请求无需@RequestBody,修改为:
@GetMapping("/forum-reviews/{forumId}") public List<Review> getReviewsByForumId(@PathVariable Long forumId) { return reviewRepository.getReviewsUsingForumId(forumId); }
2. 关联实体绑定优化
在Service层手动查询关联实体,校验其合法性,避免无效id导致的异常:
@Service public class ReviewService { @Autowired private ReviewRepository reviewRepository; @Autowired private AccountRepository accountRepository; @Autowired private ForumRepository forumRepository; public Review createReview(Review review) { Account account = accountRepository.findById(review.getAccount().getId()) .orElseThrow(() -> new RuntimeException("指定账号不存在")); Forum forum = forumRepository.findById(review.getForum().getId()) .orElseThrow(() -> new RuntimeException("指定论坛不存在")); review.setAccount(account); review.setForum(forum); return reviewRepository.save(review); } }
修改Controller调用Service:
@PostMapping("/review-add") public Review createReview(@RequestBody Review review) { return reviewService.createReview(review); }
内容的提问来源于stack exchange,提问作者Peter Moore
相关产品推荐
相关产品推荐

