vue.js get请求中正确传递数组参数
在使用Vue.js和axios进行GET请求时,直接传递数组参数可能会导致java.lang.IllegalArgumentException: Invalid character found in the request target异常。这是因为GET请求参数直接拼接在URL中,而数组格式不符合URL规范。本文将演示如何正确处理这种情况。
问题:
前端使用axios.get向后端/searchRoomTags接口发送GET请求,roomTags参数为数组。后端使用Spring Boot,使用@RequestParam String[] roomTags接收参数。直接传递数组导致请求解析失败。
错误代码(前端):
this.$axios .get('/searchRoomTags', { params: { pageSize: this.roomPageInfo.pageSize, roomType: encodeURI(this.roomForm.roomType), roomTags: this.searchRoomTags, // 直接传递数组 roomState: this.searchContent } }) // ...
错误代码(后端):
@GetMapping("/searchRoomTags") public PageInfo<rooms> searchRoomTags(@RequestParam String[] roomTags, Rooms room, HttpServletRequest request) { // ... }
解决方案:
将前端数组参数转换为以特定分隔符连接的字符串,后端再进行分割还原。
修改后的前端代码:
this.$axios .get('/searchRoomTags', { params: { pageSize: this.roomPageInfo.pageSize, roomType: encodeURI(this.roomForm.roomType), roomTags: (this.searchRoomTags || []).join(','), // 使用逗号分隔 roomState: this.searchContent } }) // ...
修改后的后端代码:
@GetMapping("/searchRoomTags") public PageInfo<rooms> searchRoomTags(@RequestParam String roomTags, Rooms room, HttpServletRequest request) { String[] tagsArray = roomTags.split(","); // 使用逗号分割字符串 // ... 使用 tagsArray }
此方案将roomTags数组转换为逗号分隔的字符串。后端接收字符串参数,再用逗号分割成数组。 选择的分隔符(这里用逗号)必须确保不会出现在数组元素中,否则需要选择其他分隔符,并前后端保持一致。 如果数组元素可能包含逗号,建议使用URL编码对元素进行编码后再拼接。
通过以上修改,可以确保GET请求中数组参数的正确传递,避免java.lang.IllegalArgumentException异常。 记住,前后端的分隔符必须一致。
以上就是Vue中GET请求如何正确传递数组参数?的详细内容,更多请关注知识资源分享宝库其它相关文章!
版权声明
本站内容来源于互联网搬运,
仅限用于小范围内传播学习,请在下载后24小时内删除,
如果有侵权内容、不妥之处,请第一时间联系我们删除。敬请谅解!
E-mail:dpw1001@163.com
发表评论