#Spring post controller not handling request body

1 messages · Page 1 of 1 (latest)

violet marten
#

I have a ConsultationController that needs to handle a post request that inserts data into the database, but when I send a post request to it it can't handle the data and just sets all the fields to null:

@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/consultation")
public class ConsultationController {
    @Autowired
    private final ConsultationService consultationService;


    public ConsultationController(ConsultationService consultationService) {
        this.consultationService = consultationService;
    }

    @PostMapping
    public ResponseEntity<?> createConsultation(@RequestBody ConsultationData consultationData) {
        try {
            ConsultationData response = consultationService.insert(consultationData);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error processing consultation: " + e.getMessage());
        }
    }
}
@Data
public class ConsultationData {
    private String contents;
    private String email;
    private String username;
}
{
    "contents": "Is running ok?",
    "email": "[email protected]",
    "username": "NikolaJelic"
}

And this is the error:

ConsultationData(contents=null, email=null, username=null)

I am stuck on this for almost 2h already and can't figure out what is wrong with it. I already have 10 other controllers and haven't had any issues with post and get methods, but now this one is stuck for some reason

exotic masonBOT
# violet marten I have a ConsultationController that needs to handle a post request that inserts...

Detected code, here are some useful tools:

Formatted code
@CrossOrigin(origins = "http://localhost:4200") @RestController
@RequestMapping("/consultation") public class ConsultationController {
  @Autowired
  private final ConsultationService consultationService;
  public ConsultationController(ConsultationService consultationService) {
    this .consultationService = consultationService;
  }
  @PostMapping
  public ResponseEntity<? > createConsultation(@RequestBody
  ConsultationData consultationData) {
    try {
      ConsultationData response = consultationService.insert(consultationData);
      return ResponseEntity.ok(response);
    } catch (Exception e) {
      return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error processing consultation: " + e.getMessage());
    }
  }
}
#

<@&1004656351647117403> please have a look, thanks.

violet marten
#

Turns out I had the wrong import for RequestBody All the time 🤡