本文探讨在Vue项目中使用axios发送GET请求时,如何安全有效地传递数组参数,避免URL编码错误。 许多开发者在处理包含中文或特殊字符的数组参数时会遇到问题。我们将分析一个案例,并提供解决方案。
问题: 开发者试图使用axios的GET请求将前端数组this.searchRoomTags
传递到后端接口/searchRoomTags
。前端代码直接在params
对象中传递数组,但后端使用@RequestParam String[] roomTags
接收参数,导致java.lang.IllegalArgumentException: Invalid character found in the request target
错误。此错误通常与GET请求的URL参数编码和服务器端参数处理有关。
前端代码(错误示例):
this.$axios
.get('/searchRoomTags', {
params: {
pageSize: this.roomPageInfo.pageSize,
roomType: encodeURI(this.roomForm.roomType),
roomTags: this.searchRoomTags,
roomState: this.searchContent
}
})
// ...
后端代码(Java Spring Boot):
@CrossOrigin
@GetMapping("/searchRoomTags")
@ResponseBody
public PageInfo searchRoomTags(@RequestParam String[] roomTags, Rooms room, HttpServletRequest request) {
// ...
}
错误原因: 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
}
})
// ...
后端代码修改: 后端需要修改接收参数的方式,例如使用@RequestParam String roomTags
,然后在后端代码中使用逗号(或其他选择的分割符)将字符串分割成数组。
注意事项: 选择合适的分割符,并确保该分隔符不会出现在数组元素中。如果数组元素可能包含该分隔符,则需要选择其他分隔符或使用更复杂的编码方式,例如JSON编码。 这种方法简单易行,但对于复杂数据结构,建议使用JSON编码,更安全可靠。