前端PUT请求后台接收的参数不完整

昨天改一个bug,大致问题是前端发起的PUT请求,参数为IDpageNopageSize(字面意思),然后返回数据总是pageNo=1,pageSize=10条件下的数据,无论我怎么改变传参值,返回数据都是一样。

  1. 首先纯后台测试没有问题,接口无误。后台(JAVA)接收参数的方法如下,对pageNopageSize连个参数没有进行额外的赋值:
/**
	  * 订单详情
	  * 接单明细页面
	  * @param itemReq
	  * @return
	  */
	 @AutoLog(value = "order_item-订单详情")
	 @ApiOperation(value = "order_item-订单详情", notes = "order_item-订单详情")
	 @PutMapping(value = "/queryItemByNum")
	 public Result<?> queryItemByNum(@RequestBody ItemReq itemReq,
									 @RequestParam(name = "pageNo",defaultValue = "1") Integer pageNo,
									 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
		 Page<OrderItem> page = new Page(pageNo, pageSize);
		 Map<String, Object> map = orderItemService.queryOrderItemByOrderId(page, itemReq.getInfoId());
		 return Result.ok(map);
	 }
  1. 前端请求代码:(其中putAction封装了axios中的PUT操作)
putAction('URI地址', {
		    itemId: this.info.itemId,
		    infoId: this.info.infoId,
		    pageNo: this.ipagination.current,
		    pageSize: this.ipagination.pageSize,
		  }).then((res) => {
		    if (res.success) {
		      console.log(res.result.orderItem)
		      //....省略其他逻辑
		    }
		  })

/*补充对putAction的封装*/
export function putAction(url,parameter) {
  return axios({
    url: url,
    method:'put',
    data: parameter
  })
}
  1. 后来和后端的同学进行联调,发现后端并没有接受到pageNopageSize的参数值,所以一直使用默认值pageNo=1,pageSize=10,导致我始终无法获得正确的返回值。

问题原因: 前端传参格式错误。
根本原因是Spring/SpringBoot(后端)对于参数的接收有两种格式,也就是@RequestBody@RequestParam。简单来说,@RequestBody会去解析参数中的JSON数据,而@RequestParam接收不到JSON数据。这样就导致,当我们前端把四个参数itemId,infoId,pageNo,pageSize封装在一个对象中一起传到后端时,这个对象会被解析成JSON格式并由@RequestBody来解析,而对应的ItemReq对象中并没有pageNo,pageSize这两个属性,所以这两个参数会被忽略,而前端又没有另外单独的传参,因此后端最后会采用defaultValue标注的默认值。

参考这篇文章:@RequestBody和@RequestParam区别

解决方案: 前端需要将pageNo,pageSize单独拼接到请求体中:

putAction('URI地址' + `?pageNo=${this.ipagination.current}&pageSize${this.ipagination.pageSize}`, {
		    itemId: this.info.itemId,
		    infoId: this.info.infoId,
		  }).then((res) => {
		    if (res.success) {
		      console.log(res.result.orderItem)
		      //....省略其他逻辑
		    }
		  })

版权声明:本文为Tinkerbaby原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。