Angular2 - Http POST request parameters

TypescriptAngular

Typescript Problem Overview


I'm trying to make a POST request but i can't get it working:

testRequest() {
      var body = 'username=myusername?password=mypassword';
      var headers = new Headers();
      headers.append('Content-Type', 'application/x-www-form-urlencoded');

      this.http
        .post('/api',
          body, {
            headers: headers
          })
          .subscribe(data => {
                alert('ok');
          }, error => {
              console.log(JSON.stringify(error.json()));
          });
}

I basically want to replicate this http request (not ajax) like it was originated by a html form:

URL: /api

Params: username and password

Typescript Solutions


Solution 1 - Typescript

Update for Angualar 4.3+

Now we can use HttpClient instead of Http

Guide is here

Sample code

const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
let body = new HttpParams();
body = body.set('username', USERNAME);
body = body.set('password', PASSWORD);
http
  .post('/api', body, {
    headers: myheader),
  })
  .subscribe();

Deprecated

Or you can do like this:

let urlSearchParams = new URLSearchParams();
urlSearchParams.append('username', username);
urlSearchParams.append('password', password);
let body = urlSearchParams.toString()

Update Oct/2017

From angular4+, we don't need headers, or .toString() stuffs. Instead, you can do like below example

import { URLSearchParams } from '@angular/http';

POST/PUT method

let urlSearchParams = new URLSearchParams();
urlSearchParams.append('username', username);
urlSearchParams.append('password', password);
this.http.post('/api', urlSearchParams).subscribe(
      data => {
        alert('ok');
      },
      error => {
        console.log(JSON.stringify(error.json()));
      }
    )

GET/DELETE method

    let urlSearchParams = new URLSearchParams();
    urlSearchParams.append('username', username);
    urlSearchParams.append('password', password);
    this.http.get('/api', { search: urlSearchParams }).subscribe(
      data => {
        alert('ok');
      },
      error => {
        console.log(JSON.stringify(error.json()));
      }
    )

For JSON application/json Content-Type

this.http.post('/api',
      JSON.stringify({
        username: username,
        password: password,
      })).subscribe(
      data => {
        alert('ok');
      },
      error => {
        console.log(JSON.stringify(error.json()));
      }
      )

Solution 2 - Typescript

I think that the body isn't correct for an application/x-www-form-urlencoded content type. You could try to use this:

var body = 'username=myusername&password=mypassword';

Hope it helps you, Thierry

Solution 3 - Typescript

In later versions of Angular2 there is no need of manually setting Content-Type header and encoding the body if you pass an object of the right type as body.

You simply can do this

import { URLSearchParams } from "@angular/http"


testRequest() {
  let data = new URLSearchParams();
  data.append('username', username);
  data.append('password', password);

  this.http
    .post('/api', data)
      .subscribe(data => {
            alert('ok');
      }, error => {
          console.log(error.json());
      });
}

This way angular will encode the body for you and will set the correct Content-Type header.

P.S. Do not forget to import URLSearchParams from @angular/http or it will not work.

Solution 4 - Typescript

so just to make it a complete answer:

login(username, password) {
        var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        let urlSearchParams = new URLSearchParams();
        urlSearchParams.append('username', username);
        urlSearchParams.append('password', password);
        let body = urlSearchParams.toString()
        return this.http.post('http://localHost:3000/users/login', body, {headers:headers})
            .map((response: Response) => {
                // login successful if there's a jwt token in the response
                console.log(response);
                var body = response.json();
                console.log(body);
                if (body.response){
                    let user = response.json();
                    if (user && user.token) {
                        // store user details and jwt token in local storage to keep user logged in between page refreshes
                        localStorage.setItem('currentUser', JSON.stringify(user)); 
                    }
                }
                else{
                    return body;
                }
            });
    }

Solution 5 - Typescript

These answers are all outdated for those utilizing the HttpClient rather than Http. I was starting to go crazy thinking, "I have done the import of URLSearchParams but it still doesn't work without .toString() and the explicit header!"

With HttpClient, use HttpParams instead of URLSearchParams and note the body = body.append() syntax to achieve multiple params in the body since we are working with an immutable object:

login(userName: string, password: string): Promise<boolean> {
    if (!userName || !password) {
      return Promise.resolve(false);
    }

    let body: HttpParams = new HttpParams();
    body = body.append('grant_type', 'password');
    body = body.append('username', userName);
    body = body.append('password', password);

    return this.http.post(this.url, body)
      .map(res => {
        if (res) {          
          return true;
        }
        return false;
      })
      .toPromise();
  }

Solution 6 - Typescript

If anyone is struggling with angular version 4+ (mine was 4.3.6). This was the sample code which worked for me.

First add the required imports

import { Http, Headers, Response, URLSearchParams } from '@angular/http';

Then for the api function. It's a login sample which can be changed as per your needs.

login(username: string, password: string) {
    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    let urlSearchParams = new URLSearchParams();
    urlSearchParams.append('email', username);
    urlSearchParams.append('password', password);
    let body = urlSearchParams.toString()

    return this.http.post('http://localhost:3000/api/v1/login', body, {headers: headers})
        .map((response: Response) => {
            // login successful if user.status = success in the response
            let user = response.json();
            console.log(user.status)
            if (user && "success" == user.status) {
                // store user details and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify(user.data));
            }
        });
}

Solution 7 - Typescript

angular: 
    MethodName(stringValue: any): Observable<any> {
    let params = new HttpParams();
    params = params.append('categoryName', stringValue);

    return this.http.post('yoururl', '', {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      }),
      params: params,
      responseType: "json"
    })
  }
 
api:   
  [HttpPost("[action]")]
  public object Method(string categoryName)

Solution 8 - Typescript

I was having problems with every approach using multiple parameters, but it works quite well with single object

api:

    [HttpPut]
    [Route("addfeeratevalue")]
    public object AddFeeRateValue(MyValeObject val)

angular:

var o = {ID:rateId, AMOUNT_TO: amountTo, VALUE: value};
return this.http.put('/api/ctrl/mymethod', JSON.stringify(o), this.getPutHeaders());


private getPutHeaders(){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return new RequestOptions({
        headers: headers
        , withCredentials: true // optional when using windows auth
    });
}

Solution 9 - Typescript

I landed here when I was trying to do a similar thing. For a application/x-www-form-urlencoded content type, you could try to use this for the body:

var body = 'username' =myusername & 'password'=mypassword;

with what you tried doing the value assigned to body will be a string.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChristopherView Question on Stackoverflow
Solution 1 - TypescriptFrank NguyenView Answer on Stackoverflow
Solution 2 - TypescriptThierry TemplierView Answer on Stackoverflow
Solution 3 - TypescriptVStoykovView Answer on Stackoverflow
Solution 4 - TypescriptdangView Answer on Stackoverflow
Solution 5 - Typescript333MattView Answer on Stackoverflow
Solution 6 - TypescriptKrishnadas PCView Answer on Stackoverflow
Solution 7 - TypescriptMuniyanView Answer on Stackoverflow
Solution 8 - TypescriptSonic SoulView Answer on Stackoverflow
Solution 9 - TypescriptadongoView Answer on Stackoverflow