私はangular2の初心者です。私のサーバー(spring)は、その応答ヘッダにset-cookieの値で認証を応答します。
次のAPIコールで、そのクッキーをリクエストヘッダに設定するにはどうしたらよいでしょうか。
いろいろと検索してみましたが、適当な解決策が見つかりません。
HTTP.get()または
http.post()][1] メソッドの一部として、[
RequestOptionsArgs`]2 を指定することができます。
必要な Auth ヘッダーを指定するには、RequestOptionsArgs
の Headers
を使用します。
大まかな例として、以下をご覧ください。
class PeopleComponent {
constructor(http: Http) {
let customHeaders: Headers = new Headers();
customHeaders.append('myHeaderName', 'myHeaderValue');
http.get('http://my.web/service', { headers: customHeaders })
.map(res => res.json())
.subscribe(people => this.people = people);
}
}
クッキーは、あなたのドメインに保存された後、あなたが行うすべての呼び出しに自動的に添付されます。 あなたは何か他のことを間違っています。RESTコールに認証データを自動的に添付する仕組みを作りたい場合は、カスタムHttpInterceptorを作成するこのチュートリアルを参照してください。
https://medium.com/aviabird/http-interceptor-angular2-way-e57dc2842462
CORSシナリオの場合、RequestOptionsにtrueに設定したwithCredentialsプロパティを追加する必要があります。以下は、私がHTTPヘルパーに実装した方法のスニペットである。
get(resource: string) {
return this.http.get(`/api/${resource}`, this.getRequestOptions())
.map(result => result.json())
.catch(e => e.status === 401 ? Observable.throw('Unauthorized') : e.json());
}
post(resource: string, body: any) {
return this.http.post(`/api/${resource}`, body, this.getRequestOptions())
.map(result => result.json())
.catch(e => e.status === 401 ? Observable.throw('Unauthorized') : e.json());
}
private getRequestOptions() {
const headers = new Headers({
'Content-Type': 'application/json',
});
return new RequestOptions({headers: headers, withCredentials: true});
}