3

I start work with angular 2 and typeScript , all work great, but when i work with rest api (POST) in console log i get Response {_body: "", status: 204, statusText: "Ok", headers: Headers, type: 2… } , despite i passed the true param for login this is my code

 authentification(){
        var headers = new Headers();
          headers.append('Content-Type', 'application/x-www-form-urlencoded');
        // headers.append('Content-Type', 'application/json');
       return this.http.post(this._postUrl,JSON.stringify({username:"abc",password:"abc"}),{headers:headers});
    }

and this is my web service

 @POST
    @Path("/admin")
    @Consumes("application/x-www-form-urlencoded")
    public User getDate(@HeaderParam("username")String username,@HeaderParam("password")String password) throws Exception{
        try {
            String passwordC =  AESCrypt.encrypt(password);
            User u = userService.login(username, passwordC);
            return u;
            
        } catch (Exception e) {
            return null;
        }
    }

i think problem in my web service param in string and in angular param is json
any one can help me please and thanks.

A.khalifa
  • 2,366
  • 3
  • 27
  • 40

1 Answers1

7

For form-urlencoded content type you need to send data in query string format with key=value pairs. You can build this string with the help of URLSearchParams class from http module. In your case it can look something like this:

authentification() {

    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

    var params = new URLSearchParams();
    params.append('username', 'abc');
    params.append('password', 'abc'); // .toString() => username=abc&password=abc

    return this.http.post(this._postUrl, params.toString(), {headers});
}
dfsq
  • 191,768
  • 25
  • 236
  • 258