Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 http post request with x-www-form-urlencoded data

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)
                    );
    }
}
like image 795
Atul Rauthan Avatar asked Jul 31 '18 04:07

Atul Rauthan


1 Answers

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": ""
    }
  }
}
like image 187
Avram Virgil Avatar answered Sep 20 '22 18:09

Avram Virgil