skip to Main Content

It appears that there is an issue passing the playerId parameter from the frontend to the backend in a React app. The createGame function in the Spring controller is set up to receive a playerId parameter, but the value is not being properly passed from the frontend using Axios. It has been attempted to use a Long and a String for the playerId, but the issue persists.
Still getting status 400 !

Spring

React

  1. Store it as a String parameter.
  2. I used @PathVariable.
  3. I tried to direct write the parameter in Postman.
  4. I tried change endpoint.
  5. Another endpoint (/login) which i’m not showing works good so no problem with proxy.

2

Answers


  1. Chosen as BEST ANSWER

    Daniel's answer is correct but I overwrite the code like this:

    @PostMapping("/games")
    public ResponseEntity<String> createGame(@RequestBody Map<String, Object> requestParams) {
        try {
            Long playerId = Long.parseLong(requestParams.get("playerId").toString());
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
            String gameCreated = now.format(formatter);
            Player player = playerRepository.findById(playerId).orElse(null);
            if (player == null) {
                return ResponseEntity.notFound().build();
            }
            Game game = new Game(gameCreated);
            gameRepository.save(game);
            GamePlayer gamePlayer = new GamePlayer(game, player);
            gamePlayerRepository.save(gamePlayer);
            return ResponseEntity.ok("Game created successfully!");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to create game.");
        }
    }
    

    And the React will be send like this:

    const handleClick = async () => {
        try {
          const response = await axios.post(`/api/games?playerId=${parseInt(storedPlayerId)}`);
          console.log(response.data);
        } catch (error) {
          console.log(error.response.data);
          // handle the error
        }
    };
    

  2. In shared React screenshot – it looks like you send a JSON body.

    However, in Spring Controller – @RequestParam is used.

    It looks like you either need to change React part to call URL like ‘/api/games/{playerId}’ (so playerId would be passed as part of URL) or update Spring Controller to accept @RequestBody (and create a class with field ‘playerId’) – so whole object could be passed as request body.

    As currently React sends a body – but Spring is looking for a URL query param. Both parts need to do same thing – whatever it will be.

    Spring changes would look like:

    public ResponseEntity<String> createGame(@RequestBody PlayerRequest playerRequest) {
        Long playerId = playerRequest.getPlayerId();
        // other code goes here
    }
    
    public class PlayerRequest {
        private Long playerId;
    
        public Long getPlayerId() {
            return playerId;
        }
    
        public void setPlayerId(Long playerId) {
            this.playerId = playerId;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search