How to pass Array param in axios get to spring controller?

Viewed 7487

I am trying to pass array of names to spring controller using axios get request.if i try to pass single value in params it works fine but if pass array in params then i am getting error "CORS header ‘Access-Control-Allow-Origin’ missing". I tried this

this is url

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

taskAction.js

var request = {
params: {
name : JSON.parse(localStorage.getItem('name')) 
   }
} 
const res = await axios.get(`http://localhost:8080/onlineshopping/view/category/products`,request);

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

but this is not working

My spring controller

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

    Map<String, Object> mapproducts = new HashMap<String, Object>();

    for (String Str : name) {
        System.out.println("name " + Str);
    }
1 Answers

You can use querystring parsing and stringifying library '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
   });
};

you will get url like this

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

and in spring controller you can split string using

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

spring controller

@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*"));
Related