在vue项目中使用axios发送get请求时,如何正确传递数组参数至关重要。本文将通过一个案例分析,讲解如何避免因数组参数传递不当导致的java.lang.illegalargumentexception: invalid character found in the request target异常。
问题描述:
开发者尝试使用axios的GET请求,向/searchRoomTags接口传递一个包含房间标签的数组this.searchRoomTags。前端代码如下:
this.$axios
.get('/searchRoomTags', {
params: {
pageSize: this.roomPageInfo.pageSize,
roomType: encodeURI(this.roomForm.roomType),
roomTags: this.searchRoomTags,
roomState: this.searchContent
}
})
.then(Response => {
if (Response.data) {
this.searchSuccessHandle(Response)
}
})
后端使用Spring Boot框架,代码如下:
@CrossOrigin
@GetMapping("/searchRoomTags")
@ResponseBody
public PageInfo<rooms> searchRoomTags(@RequestParam String[] roomTags, Rooms room, HttpServletRequest request) {
logger.info("用户开始根据房间标签进行查找————————");
request.getSession().removeAttribute("condition");
room.setCurrentPage(1);
System.out.println("roomTags:" + roomTags);
PageInfo<rooms> pageInfo = null;
logger.info("客房查询成功!");
return pageInfo;
}
然而,前端请求后,后端抛出java.lang.IllegalArgumentException: Invalid character found in the request target异常。
问题原因分析:
GET请求的参数会直接拼接在URL中。数组对象无法直接在URL中表示。直接传递数组对象会导致URL格式错误,从而引发异常。
解决方案:
将数组转换为以逗号分隔的字符串。修改后的前端代码如下:
this.$axios
.get('/searchRoomTags', {
params: {
pageSize: this.roomPageInfo.pageSize,
roomType: encodeURI(this.roomForm.roomType),
roomTags: (this.searchRoomTags || []).join(','),
roomState: this.searchContent
}
})
.then(Response => {
if (Response.data) {
this.searchSuccessHandle(Response)
}
})
这段代码使用join(',')方法将this.searchRoomTags数组转换为逗号分隔的字符串。后端仍然使用@RequestParam String[] roomTags接收参数,Spring Boot会自动将逗号分隔的字符串解析为字符串数组。|| []确保this.searchRoomTags为空时,join方法不会报错。 此方法有效避免了URL格式错误。
通过以上修改,即可解决GET请求传递数组参数导致的无效字符异常问题。 记住,对于GET请求,数组参数必须先转换为字符串再传递。
以上就是Vue axios GET请求:如何正确传递数组参数避免无效字符异常?的详细内容,更多请关注知识资源分享宝库其它相关文章!
版权声明
本站内容来源于互联网搬运,
仅限用于小范围内传播学习,请在下载后24小时内删除,
如果有侵权内容、不妥之处,请第一时间联系我们删除。敬请谅解!
E-mail:dpw1001@163.com
发表评论