Frontend JSON data becomes null in backend controller

I’m having trouble with my Spring Boot app. I made a controller to get JSON from the frontend. It’s getting called okay, but when I try to print the JSON stuff, it shows up as null.

Here’s what’s happening:

  1. Frontend sends: {"username":"test", "password":"1234"}
  2. It goes to my login endpoint
  3. Controller gets called
  4. When I print username and password, they’re null

My controller looks like this:

@RestController
@RequestMapping("auth")
public class AuthController {
    @PostMapping("/login")
    public void login(User user) {
        System.out.println("User: " + user.getUsername());
        System.out.println("Pass: " + user.getPassword());
    }
}

And my User class:

public class User {
    private String username;
    private String password;
    // getters and setters
}

I tried adding @RequestBody but got an error about missing body. It worked once before, but now it’s acting weird. Any ideas what’s going on?

hmm, interesting problem! have u tried using @JsonProperty annotations on ur User class fields? sometimes spring can be picky about mapping json to objects. also, whats the exact error u get with @RequestBody? maybe theres a clue there? oh, and double-check ur content-type header in the frontend request. just brainstorming here!

hey man, sounds frustrating! have u checked ur frontend code? make sure ur sending the JSON correctly. also, try adding @RequestBody to ur method like this:

@PostMapping(“/login”)
public void login(@RequestBody User user) {
// ur code here
}

if that doesn’t work, maybe check ur spring boot config. hope this helps!

I’ve encountered a similar issue before, and it sounds like there might be a problem with how your application is handling the incoming JSON data. Have you checked if your Spring Boot application is configured to automatically parse JSON requests? Make sure you have the appropriate dependencies in your pom.xml or build.gradle file, particularly for Jackson or another JSON processor.

Also, try adding the @RequestBody annotation to your login method parameter, like this:

@PostMapping("/login")
public void login(@RequestBody User user) {
    // Your code here
}

If you’re still getting an error about a missing body, double-check that your frontend is sending the data correctly and that the content type is set to ‘application/json’ in the request headers. It’s also worth verifying the exact error message you’re receiving, as it could provide more clues about what’s going wrong in the communication between your frontend and backend.