Angular2-Http POST 请求参数

我正在尝试发送一个 POST 请求,但是我不能让它工作:

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

我基本上想复制这个 http 请求(而不是 ajax) ,就像它是由 html 表单发起的一样:

网址:/api

用户名和密码

260977 次浏览

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

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.

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

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;
}
});
}

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.

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
});
}

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));
}
});
}

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