springboot开发中 以POST方式向后台传递json数据的时候参数值为null

时间:2024-03-16 12:33:35

自己写了一个简单的springboot后台代码,当我用postman以post方式向后台传递json对象时,后台对象的参数值总是为null,找了好久终于解决了,下面分享一下我的解决问题艰辛路程。

springboot开发中 以POST方式向后台传递json数据的时候参数值为null

springboot开发中 以POST方式向后台传递json数据的时候参数值为null

明明我传了参数值,但是debug调试的时候就是获取不到。

1.首先,我的controller中在参数前加了@RequestBody

springboot开发中 以POST方式向后台传递json数据的时候参数值为null

具体原因参考:https://blog.csdn.net/u012843873/article/details/80243340,以下是具体内容(害怕博主删了找不到,干脆就直接粘贴过来了)

/**************************帖子内容************************************************/

我的错误原因就是因为,在spring注解开发中,使用get或者是post请求的时候,就是需要这些注意事项 
这里写图片描述 
springboot开发中 以POST方式向后台传递json数据的时候参数值为null

springboot开发中 以POST方式向后台传递json数据的时候参数值为null

就是这两个地方搞混,后台就会拿不到前台传递的json数据

/**************************帖子内容************************************************/

2.修改完上面代码,一运行又报了这个错

springboot开发中 以POST方式向后台传递json数据的时候参数值为null

“Content type 'text/plain;charset=UTF-8' not supported”,网上又是一通百度,找到的答案是数据传输格式选择错误,修改为下面即可。

springboot开发中 以POST方式向后台传递json数据的时候参数值为null

3.以上是通过postman测试的,具体放到前台项目中,因为我前台做的是跨域访问,又遇到了一系列的问题。

a.错误信息:Resolved exception caused by handler execution: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'name': was expecting 'null', 'true', 'false' or NaN; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'name': was expecting 'null', 'true', 'false' or NaN

原因前台ajax请求传递的data参数格式不正确。

springboot开发中 以POST方式向后台传递json数据的时候参数值为null

解决方法参考:https://blog.csdn.net/javaee_sunny/article/details/52576710

b.错误信息:Access to XMLHttpRequest at 'http://localhost:8080/api/user/addUser' from origin 'http://localhost:8088' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这个就是跨域请求出错的问题。解决方法参考:https://blog.csdn.net/m0_37836194/article/details/79173463,https://blog.csdn.net/xuedapeng/article/details/79076704

springboot开发中 以POST方式向后台传递json数据的时候参数值为null