Home > Enterprise >  POST request from Angular to SpringBoot API not sending parameters
POST request from Angular to SpringBoot API not sending parameters

Time:02-03

I have this code, where I send an object to the API:

  validateLogin(user:User):Observable<string>{
    console.log(JSON.stringify(user));
    return this.http.post<string>(`http://localhost:8080/login/login`, user).pipe(
      map((resp)=>{
        return this.repareString(JSON.stringify(resp));
      })
    )
  }

I don't see anything wrong, but Spring Boot says "required request parameter 'user' for method parameter type String is not present". I've also tried sending it as a JSON object but it says the same. I believe that this is caused by the code in angular, that's why I post it here.

@RestController
@RequestMapping("/login")
public class LoginController {

    @PostMapping("/login")
    public static String login(@RequestParam String user) throws Exception{
        System.out.println(user);
        Login l = new ObjectMapper().readValue(user, Login.class);
        if(l.checkUser().equals("ok")){
            if(l.checkPassword().equals("ok")){
                return "logged";
            } else {
                return l.checkPassword();
            }
        }

        return l.checkUser();


    }


}

And the Login class:

public class Login extends Database{
    public String email;
    public String pass;
    public Statement stm;

    public Login(String email, String pass) throws Exception{
        this.email = email;
        this.pass = pass;
        this.stm = (Statement) this.con.createStatement();
    }

I have tried sending it as a JSON string and I've also tried sending the object properties individually as various params.

CodePudding user response:

Change your controller like this:

@RestController
@RequestMapping("/login")
public class LoginController {
@PostMapping("/login")
public static String login(@RequestBody Login login) throws Exception{
    System.out.println(login);
    
    if(login.checkUser().equals("ok")){
        if(login.checkPassword().equals("ok")){
            return "logged";
        } else {
            return login.checkPassword();
        }
    }

    return login.checkUser();

    }
}
  • Related