6

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
  • have to configured CORS in your Spring api? Commented Jan 12, 2019 at 18:06

1 Answer 1

7

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*"));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.