Search code examples
angularjsspringresthttp-status-code-400

Spring, Angular.js 400 Bad Request


I'm having a hard time figuring out why this request encounter 400 BAD request :

{
email: "[email protected]"
lastfmUsername: "bluecun"
password: "$2a$10$if246VMeosRCNJibodEhueXGyQNiAHeJd3KVHi7WedjByECYeXO5."
username: "bluecun"
}

Here is my model and controller code :

public class User {
    private Long id;
    private String username;
    private String lastfmUsername;
    private String email;
    private String password;
...
}

@RequestMapping(value = "/register", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public
    @ResponseBody
    void register(@RequestBody User user) throws Exception {
        semanticGraphDao.saveUser(user);
    }

Thanks for the answers.


Solution

  • First you need to check if you JSON is wellformed, which means: properties surrounded by quotes and a colon between each property, for example:

    {
      "email": "[email protected]",
      "lastfmUsername": "bluecun",
      "password": "$2a$10$if246VMeosRCNJibodEhueXGyQNiAHeJd3KVHi7WedjByECYeXO5.",
      "username": "bluecun"
    }
    

    On the top of that, check the constructor of your User class. It must have a default constructor:

    public class User {
        private Long id;
        private String username;
        private String lastfmUsername;
        private String email;
        private String password;
    
        public User() {
          
        }
        
        // Getters and Setters
    }
    

    And finally, check Spring boot logs - probably it is showing some kind of exception from Jackson, which will guide you on how to solve the mapping issue.