Angular 5 HttpClient: send POST parameters as URL encoded string

Angular 5.0.1

I am looking at the docs for Angular HttpClient: https://angular.io/guide/http , but I can't imagine how to send POST parameters as a URLEncoded string instead of a JSON string. For example, my Java client clients will send this default value:

username=test%40test.com&password=Password1&rolename=Admin

But Angular wants to send as Json by default:

{"username":"test@test.com","password":"Password1","rolename":"Admin"}

Here is my code:

    let body = {
      username: "test@test.com",
      password: "Password1",
      rolename: "Admin"
    };

 let headers = new HttpHeaders();
    headers = headers.set("Content-Type", "application/x-www-form-urlencoded");


    this.http.post(this.baseUrl, body, {
      headers: headers,
    })
      .subscribe(resp => {
      console.log("response %o, ", resp);
    });

I also tried adding HttpParams:

let  httpParams = new HttpParams();
httpParams.append("username", "test@test.com");
httpParams.append("password", "Password1");
httpParams.append("rolename", "Admin");

...
headers: headers,
      params: httpParams

But HttpParams don't seem to have an effect.

Any idea how the url to encode the request instead of Json?

+4
source share
2 answers

append()returns the object new HttpParams , so you need to make a small modification to the code HttpParams. Try the following:

let httpParams = new HttpParams()
    .append("username", "test@test.com")
    .append("password", "Password1")
    .append("rolename", "Admin");

append, HttpParams . , append, HttpParams .

+3

, HttpParam .

:

let httpParams = new HttpParams()
    .append("username", "test@test.com")
    .append("password", "Password1")
    .append("rolename", "Admin");

, . , . , .

0

Source: https://habr.com/ru/post/1689716/


All Articles