8

I have been trying to make a post request to my backed API to post some data. I have tried this API using postman and it works fine and the data is returned properly. However, when I try to do the same from my ionic-angular app, it doesn't work at all. I have tried most of the methods available on the web, but to no avail. I am building this app with Angular v6.0.8 and Ionic framework v4.0.1. The API expects application/x-www-form-urlencoded data in the request body (includes username, password and grant_type). I have tried using both legacy http and the new httpClient module but no luck. So far, I have tried using URLSearchParams/JSONObject/HttpParams for creating the body of the request. For headers I used HttpHeaders() to send application/x-www-form-urlencoded as Content-Type. None of these methods work.

Can anyone help me here?

PFB one of the methods I've tried so far.

Thanks, Atul

import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class AuthService {

    constructor(private http: HttpClient) {

    }

    signin(username: string, password: string){
        const formData = new FormData();
        formData.append('username', username);
        formData.append('password', password);
        formData.append('grant_type', 'password');

        this.http.post(apiUrl,formData,
                      {
                          headers: new HttpHeaders({
                            'Content-Type':'application/x-www-form-urlencoded'
                          })
                      }
                    )
                    .subscribe(
                        (res) => {
                            console.log(res);
                        },
                        err => console.log(err)
                    );
    }
}
4
  • 1
    Can you add some code? (POST request code) Commented Jul 31, 2018 at 4:41
  • I have added some code. Please review. Thanks @anuradha. Commented Jul 31, 2018 at 4:44
  • You dont need to JSON.stringify(formData) just pass the formData as the second parameter for the http.post method Commented Jul 31, 2018 at 4:46
  • 1
    @Anuradha: I did that, but i get this error. error : {error: "unsupported_grant_type"} Commented Jul 31, 2018 at 4:52

5 Answers 5

21

I was trying to just get an oauth token from an endpoint, and what I can say it is really hard to find a working answer.

Below is how I made it work in Angular 7 but this will also work in Angular 6

import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';

    login(user: string, password: string) {
        const params = new HttpParams({
          fromObject: {
            grant_type: 'password',
            username: user,
            password: password,
            scope: 'if no scope just delete this line',
          }
        });

        const httpOptions = {
          headers: new HttpHeaders({
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Basic ' + btoa('yourClientId' + ':' + 'yourClientSecret')
          })
        };

        this.http.post('/oauth', params, httpOptions)
          .subscribe(
            (res: any) => {
              console.log(res);
              sessionStorage.setItem('access_token', res.access_token);
              sessionStorage.setItem('refresh_token', res.refresh_token);
            },
            err => console.log(err)
          );
      }

If you get cors errors just set up a angular proxy:

//proxy.conf.json
{
  "/oauth": {
    "target": "URL TO TOKEN ENDPOINT",
    "changeOrigin": true,
    "secure": false,
    "logLevel": "debug",
    "pathRewrite": {
      "^/oauth": ""
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I can't thank you enough, you saved my time a lot. Use proxy config if you face CORS error it will work as needed.
I wanted to thank you as well, for other I tired passing heads in the proxy config but that did not work. I used the above suggestion and it works fantastic.
7

You dont need to JSON.stringify(formData) just pass the formData as the second parameter for the http.post method.

create a instance of FormData. And the append the values that you need to send using the formData.append().

And the httpHeaders like this.

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/x-www-form-urlencoded'
  })};

const formData = new FormData();
formData.append('username', username);
formData.append('password', password);
formData.append('grant_type', 'password');

this.http.post(apiUrl,formData,httpOptions)
                    .subscribe(
                        (res) => {
                            console.log(res);
                        },
                        err => console.log(err)
                    );

3 Comments

Thanks for your response. If I do this, I still get the unsupported grant type error.error : {error: "unsupported_grant_type"} headers : HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
I placed this ... getting error - "TypeError: Cannot read property 'append' of undefined" .. should I need to import something ?
HttpParams is immutable , var body = new HttpParams().set('username', username) .set('password', password) .set('grant_type', 'password');
1

Please try this it worked for me:

login(user: string, password: string) {
    const params = new HttpParams({
        fromObject: {
            // grant_type: 'password',
            email: user,
            password: password,
            // scope: 'if no scope just delete this line',
        }
    });
    
    const httpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/x-www-form-urlencoded'
            // 'Authorization': 'Basic ' + btoa('yourClientId' + ':' + 'yourClientSecret')
        })
    };
    
    this.http.post(this.apiUrl+"/ecs/JSON/login.php", params, httpOptions)
             .subscribe((res: any) => {
                 console.log(res);
                 // sessionStorage.setItem('access_token', res.access_token);
                 // sessionStorage.setItem('refresh_token', res.refresh_token);
             },
                 err => console.log(err)
             );

Comments

0
The key "grant_type" may not be taking due to underscore. Try removing underscore.

import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class AuthService {

    constructor(private http: HttpClient) {

    }

    signin(username: string, password: string){
        const formData = {
       'username': 'abc',
       'password': 'abc@123',
       'granttype': 'abc@123'
       }

        this.http.post(apiUrl,formData)
                    .subscribe(
                        (res) => {
                            console.log(res);
                        },
                        err => console.log(err)
                    );
    }
}

3 Comments

You mean remove underscore and keep the space between grant and type?
Just 'granttype'
Still the same result. Unsupported grant type.
0

Below one worked for me in latest angular version as of now...

login(username: string, password: string) {
    const params = new HttpParams().set("username", username).set("password",password);

    let myHeaders = {
      headers: new HttpHeaders()
        .set('Content-Type', 'application/x-www-form-urlencoded'),
        params:params
    }
    this.httpClient
      .post(urlConsts.hostport + urlConsts.login, {}, myHeaders)
      .subscribe(
        (res) => {
          console.log('RES::', res);
        },
        (error: HttpErrorResponse) => {
          console.log('ERR::', error);
          if (error.status == 403) {
            this.snackbarShow('Invalid Credentials', 'Ok');
          }
        }
      );
  }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.