解决前端发axios请求传输数组参数给后端时,请求路径中的数组参数带中括号[]

问题描述

今天在做项目某部分功能时,后端接口接收一个数组参数,前端向后端发起axios get请求时,请求路径中的数组参数始终带有中括号[],导致后端一直报400错误…
正确请求路径:
http://127.0.0.1:9000/bridgeMonitorContent/getContentByTypeIds?monitorTypeIds=LF-SWJTU&monitorTypeIds=ND-SWJTU
实际请求路径:
http://127.0.0.1:9000/xboot/bridgeMonitorContent/getContentByTypeIds?monitorTypeIds[]=LF-SWJTU&monitorTypeIds[]=ND-SWJTU

解决办法

网上查阅资料后,发现是因为axios的params参数在序列化时的格式设置不正确而导致的,在axios的配置项中提供paramsSerializer方法可以对params进行序列化:

  1. 引入qs序列化库
import qs from 'qs'
  1. 封装请求方法
export const getRequest = (url, params) => {
    
    
    let accessToken = getStore('accessToken');
    return axios({
    
    
        method: 'get',
        url: `${
      
      baseApi}${
      
      url}`,
        params: params,
        paramsSerializer: params => {
    
    
            return qs.stringify(params, {
    
     indices: false })
          },
        headers: {
    
    
            'accessToken': accessToken
        }
    });
};
  1. 调用请求方法
export const getContentByTypeIds = (params) => {
    
    
    return getRequest('/bridgeMonitorContent/getContentByTypeIds', params)
}
  1. 后台接口
   @GetMapping("/getContentByTypeIds")
    @ApiOperation("通过多监测类型查询监测因素")
    public Result<List<BridgeMonitorContent>> getContentByTypeIds(@RequestParam List<String> monitorTypeIds){
    
    
        List<BridgeMonitorContent> contentByTypeId = iBridgeMonitorContentService.getMonitorContentByTypeId(monitorTypeIds);
        return new ResultUtil<List<BridgeMonitorContent>>().setData(contentByTypeId);
    }

最终效果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42194695/article/details/123010010