Post with x-www-form-urlencoded in the Angular

3

Hello, I have a POST request that is of content-type: x-www-form-urlencoded.

I need to pass some parameters on my Body, like this:

I'mdoingthisbelowtoaddmyparameterstotherequestbody:

  ObtendoToken(): Observable<string> {
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded')

    const body = new URLSearchParams();
    body.set('grant_type', 'password');
    body.set('username', 'varejo_user');
    body.set('password', 'w6h5xgtl');

    return this.http.post('${ApiDeSegurança}', body, new RequestOptions({headers: headers})).map(response => response.json());
  }

But you are returning this error:

error ":" unsupported_grant_type

I believe it is in the creation of body parameters. I can not solve it, because it is my first POST request in the angle!

Thank you in advance ....

I restarted my angled application and tried to use the same method and the error occurred again ...

New method with the same error as: unsupported_grant_type

 ObtendoToken(): Observable<string> {
  const headers = new Headers();
  headers.append('Content-Type', 'application/x-www-form-urlencoded');
  const body = {grant_type: 'password', username: 'varejo_user', password: 'w6h5xgtl'}; 

  return this.http.post('${ApiDeSegurança}', body, new RequestOptions({headers: headers})).map(response => response.json());
}
    
asked by anonymous 07.06.2018 / 21:46

2 answers

1

It looks like Body, has to be in string type and not as an object.

This way:

let grant_type = 'password';
let username = 'varejo_user';
let password = 'w6h5xgtl';
let body = 'grant_type=${grant_type}&username=${username}&password=${password}';

So it worked normally. I do not understand how it worked the first time.

The whole method looks like this:

ObtendoNovoToken(): Observable<string> {
  const header = new Headers();
  header.append('Content-Type', 'application/x-www-form-urlencoded');

  let grant_type = 'password';
  let username = 'varejo_user';
  let password = 'w6h5xgtl';
  let body = 'grant_type=${grant_type}&username=${username}&password=${password}';

  return this.http.post('${ApiDeSegurança}', body, new RequestOptions({headers: header})).map(response=> response.json())
}
    
07.06.2018 / 23:09
1

tries to pass the body just as an object:

body = {
 grant_type : 'password' , 
 username: 'varejo_user' , 
 password: 'w6h5xgtl' 
} ; 

It looks like this:

ObtendoToken(): Observable<string> {
const body = {grant_type: 'password', username: 'varejo_user', password: 'w6h5xgtl'}
const headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');

return this.http.post('${ApiDeSegurança}', body, new RequestOptions({headers: headers})).map(response => response.json());
}
    
07.06.2018 / 22:00