我正在尝试发出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
参数:用户名和密码
答案 0 :(得分:94)
更新 Angualar 4.3 +
现在我们可以使用HttpClient
代替Http
指南是here
示例代码
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();
<强>已过时强>
或者你可以这样做:
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('username', username);
urlSearchParams.append('password', password);
let body = urlSearchParams.toString()
2017年10月更新
从 angular4 + ,我们不需要headers
或.toString()
个东西。相反,您可以执行以下示例
import { URLSearchParams } from '@angular/http';
POST / PUT方法
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方法
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()));
}
)
对于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()));
}
)
答案 1 :(得分:42)
我认为application/x-www-form-urlencoded
内容类型的正文不正确。你可以尝试使用它:
var body = 'username=myusername&password=mypassword';
希望它可以帮到你, 亨利
答案 2 :(得分:41)
在Angular2的更高版本中,如果您将正确类型的对象传递为Content-Type
,则无需手动设置body
标头并对主体进行编码。
你可以做到这一点
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());
});
}
这样,angular将为您编码正文,并设置正确的Content-Type
标题。
P.S。不要忘记从URLSearchParams
导入@angular/http
,否则无效。
答案 3 :(得分:8)
所以只是为了得到一个完整的答案:
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;
}
});
}
答案 4 :(得分:4)
如果有人正在努力使用角度版本4+(我的是4.3.6)。这是为我工作的示例代码。
首先添加所需的导入
import { Http, Headers, Response, URLSearchParams } from '@angular/http';
然后为api函数。它是一个登录样本,可以根据您的需要进行更改。
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));
}
});
}
答案 5 :(得分:4)
对于那些使用HttpClient而不是Http的人来说,这些答案都已过时。我开始疯狂思考,#34;我已经完成了URLSearchParams的导入,但是如果没有.toString()和显式标题,它仍然无法工作!&#34;
使用HttpClient,使用HttpParams而不是URLSearchParams并注意body = body.append()
语法,以便在我们处理不可变对象时在主体中实现多个参数:
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();
}
答案 6 :(得分:0)
我在使用多个参数的每个方法都遇到了问题,但它对单个对象
非常有效api:
[HttpPut]
[Route("addfeeratevalue")]
public object AddFeeRateValue(MyValeObject val)
角:
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
});
}
答案 7 :(得分:0)
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)
答案 8 :(得分:-2)
var body = 'username' =myusername & 'password'=mypassword;
您尝试将指定给body的值设为字符串。