ernes3
ernes3

Reputation: 101

Send data in a http post in angular 2?

I'm trying to send data with http post following differents threads, but I can't do it. I need to send this data, tested in postman.

Headers. Content-Type: application/x-www-form-urlencoded Authorization: Basic user:pass

Body. grant_type: password scope: profile

This is my code.

login() {

    let url = URL_LOGIN;

    let headers = new Headers(
      {
        'Content-Type': 'application/json',
        'Authorization': 'Basic user:pass'
      });

    let body = {
      'grant_type': 'password',
      'scope': 'profile'
    }

    return this.http.post(url, body, { headers: headers })
      .map((response: Response) => {
        var result = response.json();
        return result;
      })

  }

Thanks in advance!!

Upvotes: 0

Views: 1391

Answers (1)

Hung Tran
Hung Tran

Reputation: 365

There are two things you need to modify:

  1. Your headers passed into the http post method missed one step. It should contain the following:

    let options = new RequestOptions({ headers: headers });
    

    Ensure you import RequestOptions from @angular/http

    Then pass options into your post method as follows:

    return this.http.post(url, body, options)...
    
  2. The http post method body can only be a string. Therefore, it should be as follows:

    let body = 'grant_type=password' + '&scope=profile';
    

Upvotes: 1

Related Questions