1

I have a weird situation that may be because I missed something that I didn't realized or know. I am creating a simple login UI using Angular and call the Web API created in Java.

The Java web API function is as follows:

@RequestMapping(value = "/logon", method = RequestMethod.POST, produces = {"application/json"})
@ResponseBody
public String logon(
        @RequestParam(value = "userID", required = true) String userID,
        @RequestParam(value = "password", required = true) String password,
        HttpServletRequest request)

Now if I use the http.post as follows:

login(username: string, password: string) {
    return this.http.post(this.url+"/security/logon/", 
                          JSON.stringify({ userID: username, password: password }) )

Then I get the following error in the Google Chrome browser:

POST http://localhost:8080/logon/ 400 (Required String parameter 'userID' is not present)

But if I change the code as follows:

login(username: string, password: string) {
    var usrpwd = "userID=" + username + "&password=" + password;
    return this.http.post(this.url+"/security/logon?"+usrpwd, usrpwd )

It work perfectly. Am I missing something? Why the second parameter of http.post that should be the parameter passed not seems to be working?

2 Answers 2

2

You are defining your endpoint url with two mandatory parameters, and such parameters must be in the url (check here), so when you make a request to your endpoint, the url must be :

http://localhost:8080/logon?userID=yourUserId&password=yourUserPassword

In the first implementation you are not adding the query parameters to the url so the request is made to the url http://localhost:8080/logon/ as it doesn't have the required parameters, your web tier is returning the 400 http code, which implies a bad request (because again, your url doesn't contains the required parameters).

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for the enlightenment. Now I understand at least there are 2 ways to pass parameters to a web API.
Glad to know it works for you :) if you considerer the answer useful mark it as accepted answer.
0

 constructor(private http:HttpClient){

}

login(usrName,usrPwd){

let body = {userName:usrName, userPwd:usrPwd}; this.http.post("http://localhost:5000/security/login", body) .subscribe( res => console.log(res), error => console.log(error) ) }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.