[英]Angular2/Http (POST) headers
在执行POST请求时我无法更改标头。 我尝试了几件事:
简单的课程:
export class HttpService {
constructor(http: Http) {
this._http = http;
}
}
我试过了:
testCall() {
let body = JSON.stringify(
{ "username": "test", "password": "abc123" }
)
let headers = new Headers();
headers.append('Content-Type', 'application/json'); // also tried other types to test if its working with other types, but no luck
this._http.post('http://mybackend.local/api/auth', body, {
headers: headers
})
.subscribe(
data => { console.log(data); },
err => { console.log(err); },
{} => { console.log('complete'); }
);
}
2:
testCall() {
let body = JSON.stringify(
{ "username": "test", "password": "abc123" }
)
let headers = new Headers();
headers.append('Content-Type', 'application/json'); // also tried other types to test if its working with other types, but no luck
let options = new RequestOptions({
headers: headers
});
this._http.post('http://mybackend.local/api/auth', body, options)
.subscribe(
data => { console.log(data); },
err => { console.log(err); },
{} => { console.log('complete'); }
);
}
这两个人都没有工作。 我没有忘记导入任何类。
我正在使用Google Chrome。 所以我检查了“网络”标签,我的请求就在那里,它说我的Content-Type是text / plain。
这是一个错误还是我做错了什么?
更新我忘了从Angular2 / http导入Headers类:
import {Headers} from 'angular2/http';
我认为你正在以正确的方式使用Angular2的HTTP支持。 请参阅此工作plunkr: https ://plnkr.co/edit/Y777Dup3VnxHjrGSbsr3 ? p = preview。
也许,你忘了导入Headers
类。 我前一段时间犯了这个错误,JavaScript控制台没有错误,但我试图设置的标题实际上没有设置。 例如,关于Content-Type
标头,我有text/plain
而不是application/json
。 您可以通过在导入中评论Headers
在我提供给您的plunkr中重现这一点...
这是一个完整的工作样本(包括导入):
import {Component} from 'angular2/core';
import {Http,Headers} from 'angular2/http';
import 'rxjs/Rx';
@Component({
selector: 'my-app',
template: `
<div (click)="executeHttp()">
Execute HTTP
</div>
`
})
export class AppComponent {
constructor(private http:Http) {
}
createAuthorizationHeader(headers:Headers) {
headers.append('Authorization', 'Basic ' +
btoa('a20e6aca-ee83-44bc-8033-b41f3078c2b6:c199f9c8-0548-4be79655-7ef7d7bf9d20'));
}
executeHttp() {
var headers = new Headers();
this.createAuthorizationHeader(headers);
headers.append('Content-Type', 'application/json');
var content = JSON.stringify({
name: 'my name'
});
return this.http.post(
'https://angular2.apispark.net/v1/companies/', content, {
headers: headers
}).map(res => res.json()).subscribe(
data => { console.log(data); },
err => { console.log(err); }
);
}
}
希望它对你有帮助,蒂埃里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.