function initPage(){ var location = window.location.href; var fromIndex = location.indexOf("/Shopping/"); var serviceUrl = location.substring(0, fromIndex); var params={ }; $.ajax({ url : serviceUrl + "/Shopping/userinfo/getuserlist", type : 'post', data:params, contentType : 'application/json;charset=utf-8', success : function(data) { console.log(data); }, error : function(error) { console.log('接口不通' + error); } }); }
上面是利用ajax请求后台的restful接口
接口代码如下:
/** * 获取所有满足的条件的用户 * @param params * @param response * @return * @throws IOException */ @RequestMapping(value = "/getuserlist",produces = "application/json; charset=utf-8") public @ResponseBody String getUserList(@RequestBody String params,@Context HttpServletResponse response) throws IOException{ log.info("-----------------开始调用getuserlist------------------------------------"); JSONArray json_arr=userService.getUserListInfo(); log.info("------------------结束调用getuserlist------------------------------------"); JSONObject json=new JSONObject(); json.put("userlist", json_arr); return BuildJsonOfObject.buildJsonOfJsonObject(json); }就这样看着还挺完美的,但是却十分的不尽人意,总是出现这样的错误
[WARN ] 2018-04-03 09:09:40 DefaultHandlerExceptionResolver@(DefaultHandlerExceptionResolver.java:384):Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String com.wdg.controller.UserController.getUserList(java.lang.String) throws java.io.IOException
我把这样的错误放到网上看了一大堆说什么异常处理啊之类的,但是我可不是想要这样的结果,我们知道的是应该怎样来解决这样的的问题
原因是后台接口有接收参数的@RequestBody 没有向后台传递参数,或者是参数为空
解决办法:
1.后台的接口参数去掉
2.前台ajax里面添加 data:params 其中params是不能为空的
希望对你有所帮助