如何将axios中的数组参数传递给spring controller?

时间:2019-01-12 09:36:22

标签: reactjs spring-boot axios

我正在尝试使用axios get request将名称数组传递给spring控制器。如果我尝试在params中传递单个值,它可以正常工作,但是如果在params中传递数组,那么我会收到错误消息“ CORS标头'Access-Control-允许来源丢失”。我尝试过了

这是网址

401

taskAction.js

@RestController
@RequestMapping(value = "/api/v1/user")
@CrossOrigin(origins = "*")
public class UserController {

  private static final Logger LOGGER = LogManager.getLogger(UserController.class);
  public static final String ROLE_USER = "ROLE_USER";



  private final AuthenticationFacade authenticationFacade;
  private final UserService userService;

  @Autowired
  public UserController(AuthenticationFacade authenticationFacade,
    UserService userService) {
    this.authenticationFacade = authenticationFacade;
    this.userService = userService;
  }

  @RequestMapping(value = "/me", method = RequestMethod.GET)
  public Optional<User> getCurrentUser() {
    LOGGER.info("Requesting /api/v1/user/me");
    return userService.findByUsername((String) authenticationFacade.getAuthentication().getPrincipal());
  }
}

但这不起作用

我的弹簧控制器

http://localhost:8080/onlineshopping/view/category/products?name[]=Alex&name[]=john

1 个答案:

答案 0 :(得分:1)

您可以使用查询字符串解析和字符串化库'qs'。

import Qs from 'qs'

params = {
name : JSON.parse(localStorage.getItem('name')) 
}

let myAxios = axios.create({
  paramsSerializer: params => Qs.stringify(params, {arrayFormat: 'repeat'})
})

const res = await 
myAxios.get(`http://localhost:8080/onlineshopping/view/category/products`, {params});

dispatch({
type: GET_CATEGORY_PRODUCTS,
payload: res.data
   });
};

您将获得这样的网址

http://localhost:8080/onlineshopping/view/category/products?name=Alex&name=john

在spring控制器中,您可以使用

Arrays.asList(name.split("\\s*,\\s*"))

弹簧控制器

@RequestMapping(value = "/view/category/products")
public Map<String, Object> viewProducts(
    @RequestParam(value = "name", required = false) String name,
    HttpServletRequest request, HttpServletResponse response) {

 List<String> name = Arrays.asList(name.split("\\s*,\\s*"));