简体   繁体   English

在请求标头Angular2中设置Cookie

[英]Set Cookie in Request Headers Angular2

I am new to angular2. 我是angular2的新手。 My server(spring) responds authentication with a set-cookie value in its response headers. 我的服务器(spring)在其响应头中使用set-cookie值响应身份验证。

How to set that cookie to the request headers for the next API calls? 如何将cookie设置为下一个API调用的请求标头?

I searched a lot, but I cannot find a suitable solution. 我搜索了很多,但我找不到合适的解决方案。

As part of the http.get() or http.post() methods you can specify the RequestOptionsArgs 作为http.get()http.post()方法的一部分,您可以指定RequestOptionsArgs

Use the Headers in the RequestOptionsArgs to specify the auth header you need. 使用RequestOptionsArgsHeaders指定所需的auth标头。

As a rough example, see below: 作为一个粗略的例子,见下文:

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

Cookies are automatically attached to every call you make after it i saved for your domain. Cookie会自动附加到您为域名保存后进行的每次通话中。 You are doing something else wrong. 你做错了什么。 In case you want to create automatic mechanism for attaching auth data to REST calls, refere to this tutorial that creates custom HttpInterceptor: 如果您想创建自动机制以将auth数据附加到REST调用,请参阅本教程以创建自定义HttpInterceptor:

https://medium.com/aviabird/http-interceptor-angular2-way-e57dc2842462 https://medium.com/aviabird/http-interceptor-angular2-way-e57dc2842462

In case of a CORS scenario, you will need to add the withCredentials property set to true in the RequestOptions. 如果是CORS方案,则需要在RequestOptions中将withCredentials属性设置为true。 Below is a snippet on how I've implemented in my HTTP helper: 下面是我在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}); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM