[英]Set Cookie in Request Headers Angular2
我是angular2的新手。 我的服务器(spring)在其响应头中使用set-cookie值响应身份验证。
如何将cookie设置为下一个API调用的请求标头?
我搜索了很多,但我找不到合适的解决方案。
作为http.get()
或http.post()
方法的一部分,您可以指定RequestOptionsArgs
使用RequestOptionsArgs
的Headers
指定所需的auth标头。
作为一个粗略的例子,见下文:
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); } }
Cookie会自动附加到您为域名保存后进行的每次通话中。 你做错了什么。 如果您想创建自动机制以将auth数据附加到REST调用,请参阅本教程以创建自定义HttpInterceptor:
https://medium.com/aviabird/http-interceptor-angular2-way-e57dc2842462
如果是CORS方案,则需要在RequestOptions中将withCredentials属性设置为true。 下面是我在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.