0

I want to pass a String array of usernames from react to Spring so that I can then get some user details for each of those usernames and finally pass this back to react as a List<String>

So far in react, I am making an array of usernames, and then passing them as the request body to spring

        const roundRobin = () => {
        const userList = []
        //Get list of entrants usernames to pass to backend
        for(let i =  0; i < entrants.length; i++){
          userList.push(entrants[i].username);
          console.log(userList);
        }
        const List = JSON.stringify(userList) 

        //API call
        apiCalls
        .getRandomUserList(List)
        .then((response) => {
          console.log(response.data);
        })
        .catch((apiError) => {
          if (apiError.response.data && apiError.response.data.validationErrors) {
            setEditErrors(apiError.response.data.validationErrors);
          }
          console.log(apiError.response.data)
          setPendingApiCall(false);
        });
        
      }

In spring my controller takes the request body as a String[]

//create a random list of members who have entered an event
    @CrossOrigin
    @GetMapping("/users/createRandomList")
    List<String> randomList(@RequestBody String[] usernames) {
        return userService.createRandomUserList(usernames);
    }

The UserService then takes the String[] and changes it to a List and calls a method which randomly rearranges the order of the Strings, it then loops through the returned List (which are a username) and gets the User from the database and adds some details about that User to a new List This is then returned to react.

public List<String> createRandomUserList(String[] randomUsernames) {
        List<String> users = new ArrayList<>();
        List<String> randomUsersList = Arrays.asList(randomUsernames);
        List<String> randomUsers = getRandomUsers(randomUsersList);
        for (String randUsernames : randomUsers) {
            User u = userRepository.findByUsername(randUsernames);
            users.add(u.getFirstname() + " " + u.getSurname() + " " + u.getHandicap());
        }
        return users;

    }

    //Create list of entrants IDs in random order for tee times.
    public List<String> getRandomUsers(List<String> userIds) {
        int size = userIds.size();
        List<String> passedList = userIds;
        List<String> entrants = new ArrayList<>();
        Random rand = new Random();
        for(int i = 0; i < size; i++) {
            int randomIndex = rand.nextInt(passedList.size());
            entrants.add(passedList.get(randomIndex));
            passedList.remove(randomIndex);
        }
        return entrants;
    }

When I try and run this in my web app though, I get an HTTP 400 error,

{timestamp: 1640902047907, status: 400, message: 'Required request body is missing: java.util.List<j…ser.UserController.randomList(java.lang.String[])', url: '/api/1.0/users/createRandomList'}

I am not sure what I am doing wrong, as far as I can tell, I am passing an array to Spring, when I console.log(List), I get ["user1","user2"]

6
  • It sounds like the List isn't put into the request body correctly. How does your getRandomUserList code look? Commented Dec 30, 2021 at 22:38
  • Hi, it is in my initial qusetion. I think I may have found a solution, from a bit of reading on this, it is suggested that we dont use RequestBody with Get requests, so I have changed this to RequestParam and it is working fine now if I send the list as a param in the api call Commented Dec 30, 2021 at 22:41
  • 1
    Oh didn't even realize your endpoint is a GET. Yeah GET request can't have a body. Commented Dec 30, 2021 at 22:43
  • The endpoint name /users/createRandomList does not follow the REST rules,see "Use nouns for naming URIs". You should name it /users?random for example. Commented Dec 30, 2021 at 23:01
  • @HanchenJiang All the requests can have a body even get request, but it is a bad practice to send a body with get request according to REST principal. a good practice is to send a body with POST requests Commented Dec 31, 2021 at 3:20

1 Answer 1

1

I think you should change the get mapping to post mapping and then use the List instead of String[], try in that way

@CrossOrigin
    @GetMapping("/users/createRandomList")
    List<String> randomList(@RequestBody List<String> usernames) {
        return userService.createRandomUserList(usernames);
}

also change service methods according to the changes

Sign up to request clarification or add additional context in comments.

2 Comments

Your answer has kept the @GetMapping but I know what you mean. Thanks
Sorry, yes that should be post mapping

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.