Angular2 - Http POST request parameters
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
Solution 1:
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:
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:
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.