Spring Boot does not recognize an Object sent from angular4's http

0

I am trying to execute a post call from an angular application to an api developed with Spring boot. What happens is that I do not bind between the object I sent and the one that is expected as a parameter. If I run it from postman sending the parameters as form-data or urlencoded works fine, but not from the application.

My code is as follows:

UserById(param: Object): any {
console.log(JSON.stringify(param));
return this._http.post('http://localhost:8080/user/userbyid', JSON.stringify(param), this.opciones()).pipe(
  map((res: Response) => {
    return res.json();
  }),
);

}

Try to send the object as JSON as seen in the coffin and without pairing and in neither of the two ways it works. An example of JSON that I send is:

{"User":"leonardo_alvarez","User2":"Usuario2"}

The API code is the following:

public class userObj {

    private String user;
    private String user2;

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getUser2() {
        return user2;
    }

    public void setUser2(String user2) {
        this.user2 = user2;
    }
}

@Autowired
private REL_UserRepository rel_userRepository;
@PostMapping(path = "/userbyid")
public @ResponseBody List<REL_User> getUser (userObj User){
    return rel_userRepository.findByUserid(User.getUser());
}

Does anyone know that this may be happening?

    
asked by Leonardo 11.05.2018 в 05:39
source

1 answer

0

Because of the code you have attached, it seems that you need to add three details:

  • Add a default constructor that is capable of instantiating an object without any parameters.
  • Add annotation @RequestBody in the parameter userObj User
  • In the PostMapping annotation it adds that the endpoint consumes a json in the following way: @PostMapping(path = "/userbyid", consumes = MediaType.APPLICATION_JSON_VALUE) .
  • Also, when launching the request to the service, it indicates in the header of the request that the Content-Type is a application/json .

    Anyway you can check this link if you have any other questions about annotation RequestBody

        
    answered by 14.05.2018 в 16:53