Vue axios GET请求:如何正确传递数组参数到后端?(数组.如何正确.后端.请求.传递...)

wufei123 发布于 2025-03-14 阅读(10)

Vue axios GET请求:如何正确传递数组参数到后端?

本文探讨在vue项目中,如何使用axios发送get请求并正确传递数组参数到spring boot后端的问题。 直接将数组作为get请求参数会引发java.lang.illegalargumentexception: invalid character found in the request target错误,因为get请求参数必须是键值对形式。

问题:前端使用axios发送GET请求到/searchRoomTags接口,传递包含this.searchRoomTags数组的params。后端使用@RequestParam String[] roomTags接收参数。

前端代码(错误示例):

this.$axios
    .get('/searchRoomTags', {
      params: {
        pageSize: this.roomPageInfo.pageSize,
        roomType: encodeURI(this.roomForm.roomType),
        roomTags: this.searchRoomTags, // 错误:直接传递数组
        roomState: this.searchContent
      }
    })
    // ...

后端代码:

@CrossOrigin
@GetMapping("/searchRoomTags")
@ResponseBody
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
      }
    })
    // ...

(this.searchRoomTags || []).join(',') 处理了this.searchRoomTags为空的情况,避免错误。 后端代码无需修改,可以直接使用String[] roomTags接收参数,然后自行分割字符串。 这种方法确保了URL格式正确,避免了无效字符的出现。

通过将数组转换为字符串,有效解决了GET请求传递数组参数的问题,实现了前端和后端的正确数据交互。

以上就是Vue axios GET请求:如何正确传递数组参数到后端?的详细内容,更多请关注知识资源分享宝库其它相关文章!

标签:  数组 如何正确 后端 

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。