使用Axios调用Spring Boot注册API时出现422验证错误排查
问题原因及修正方案
问题现象
向Spring Boot REST API发送注册POST请求时,收到「Request failed with status code 422」错误,返回信息显示firstName、password等字段存在「must not be blank」的非空验证失败问题,但确认已传入有效数据。
核心原因
你混淆了Axios与原生fetch的API用法,导致请求体数据没有正确发送给后端:
- Axios的
post方法语法为axios.post(url, data, config),第二个参数直接是请求体数据,第三个参数才是请求配置(如headers、method等) - 你当前的写法把请求体放到了第二个参数的
body属性中,实际发送给后端的请求体是一个包含method、headers、body的对象,而非真正的用户注册数据。后端无法解析到firstName等字段,因此触发非空验证失败。
修正代码
修正后的service.js
export const PostWithoutAuth = (url, body) => { // Axios.post 第二个参数直接传入请求体,第三个参数传配置(Content-Type默认是application/json,可省略) const request = axios.post(url, body, { headers: { "Content-Type": "application/json", }, }); return request; };
修正后的form.jsx
const handleSubmit = (event) => { event.preventDefault(); PostWithoutAuth("/auth/register", { firstName: firstName, lastName: lastName, username: username, password: password, roles: null }) // Axios会自动解析响应为JSON,无需调用res.json() .then((result) => { localStorage.setItem("tokenKey", result.data.accessToken); localStorage.setItem("refreshKey", result.data.refreshToken); localStorage.setItem("currentUser", result.data.userId); localStorage.setItem("username", result.data.username); }) .catch((error) => { setAlert(error.message, "error"); }); };
内容的提问来源于stack exchange,提问作者Jack
相关产品推荐
相关产品推荐

