When the front end sends an axios request to transmit array parameters to the back end, the array parameters in the request path have square brackets []

Problem Description

When working on some functions of the project today, the backend interface receives an array parameter. When the frontend initiates an axios get request to the backend, the array parameter in the request path always has square brackets [], causing the backend to report 400 errors all the time...
correct Request Path:
http://127.0.0.1:9000/bridgeMonitorContent/getContentByTypeIds?monitorTypeIds=LF-SWJTU&monitorTypeIds=ND-SWJTU
Actual Request Path:
http://127.0.0.1:9000/xboot/bridgeMonitorContent/getContentByTypeIds?monitorTypeIds[]=LF-SWJTU&monitorTypeIds[]=ND-SWJTU

Solution

After consulting the information on the Internet, it is found that the format of the params parameter of axios is incorrect during serialization. The paramsSerializer method can be provided in the configuration item of axios to serialize the params:

  1. Introduce the qs serialization library
import qs from 'qs'
  1. Package request method
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. call request method
export const getContentByTypeIds = (params) => {
    
    
    return getRequest('/bridgeMonitorContent/getContentByTypeIds', params)
}
  1. background interface
   @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);
    }

final effect

insert image description here

Guess you like

Origin blog.csdn.net/weixin_42194695/article/details/123010010