Angular2 - Http POST request parameters

I am trying to make a POST request, but I cannot get it to work:

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), for example, it was created by the html form:

URL: / api

Param: username and password

+78
angular typescript
Feb 04 '16 at 21:52
source share
9 answers

I think the body is not suitable for the content type application/x-www-form-urlencoded . You can try using this:

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

Hope this helps you, Thierry

+38
Feb 04 '16 at 22:05
source

Update for Angualar 4. 3+

Now we can use HttpClient instead of Http

Manual 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(); 



Outdated

Or you can do this:

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



October 2017 update

Starting with angular4 + , we do not need headers or .toString() . Instead, you can do as in the example below

 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 application/json 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())); } ) 
+91
Oct 15 '16 at 7:02
source

In later versions of Angular2, there is no need to manually set the Content-Type header and encode the body if you pass an object of the correct type as body .

You can just do it

 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 angular way will encode the body for you and will set the correct Content-Type header.

PS Remember to import URLSearchParams from @angular/http or it will not work.

+40
Dec 29 '16 at 2:06
source

to just give him the full 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 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; } }); } 
+6
Nov 15 '16 at 15:31
source

These answers are deprecated for those using HttpClient, not Http. I started to go crazy thinking: "I did import URLSearchParams, but it still does not work without .toString () and an explicit header!"

With HttpClient, use HttpParams instead of URLSearchParams and pay attention to the syntax body = body.append() to get several parameters 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(); } 
+4
Nov 09 '17 at 19:21
source

If someone is struggling with angular version 4+ (mine was 4.3.6) . This was a sample code that worked for me.

First add the required import

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

Then for the api function. This is a sample entry that can be changed to suit 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)); } }); } 
+3
Sep 03 '17 at 15:19
source

I had problems with each approach using multiple parameters, but it works fine with a 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 }); } 
0
Mar 02 '17 at 16:18
source

The answer suggested by Thierry Templar worked for me. thank

Here is what I did:

 const data ='username=aaaa&password=bbb&grant_type=password'; const axiosConfig = { headers: { "Content-Type": "application/x-www-form-urlencoded", "Authorization": "Basic bmltcy1jbGllbnQ6bmltcy1zZWNyZXQ=" } }; axios.post('http://10.122.22.22:8001/oauth/token', data,axiosConfig ).then(posts => { console.log('axios Data in server', posts); res.status(200); }) .catch((err)=> { console.log('Error:::::::', err); } ); 
0
Dec 15 '18 at 3:14
source

I landed here when I tried to do this. For the content type application / x-www-form-urlencoded, you can try using this for the body:

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

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

-2
Jul 04 '16 at 17:44
source



All Articles