我是angular2的新手。我的服务器(spring)在其响应头中使用set-cookie值响应身份验证。在Request Headers中设置Cookie Angular2
如何将cookie设置为下一个API调用的请求标头?
我搜索了很多,但我找不到合适的解决方案。
我是angular2的新手。我的服务器(spring)在其响应头中使用set-cookie值响应身份验证。在Request Headers中设置Cookie Angular2
如何将cookie设置为下一个API调用的请求标头?
我搜索了很多,但我找不到合适的解决方案。
Cookies是自动连接到每一个打电话给你做后我救了你的域名。 你正在做别的事情。如果你想创建自动的机制用于连接身份验证数据REST调用,参考,本教程创建自定义HttpInterceptor:
https://medium.com/aviabird/http-interceptor-angular2-way-e57dc2842462
其实,我正确地遵循了一切,我试了一切..但没有用。 angular2默认不存储cookie –
保存cookie不是Angular的工作,浏览器会为你做这件事。但奇怪的是,它不这样做。比使用这个cookie管理https://github.com/BCJTI/ng2-cookies/blob/master/README.MD –
@SibiRaj cookies与Angular无关 - 服务器将它们发回请求和任何后续请求到那台服务器会再次发送它们。你应该看看你的cookies实际发生了什么 - cookies是做你想要的正确方法。标题将起作用,但不建议。 – Askanison4
作为的http.get()
or 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 }) \t
.map(res => res.json())
.subscribe(people => this.people = people);
}
}
你能告诉我如何实现吗 –
我已经添加了一个代码示例,但是我建议您调查一下,实际上是否需要做任何特定的标头操作 - 正如别人所说的那样,Cookie通常会自动发送回服务器随着每个请求,所以你应该能够检查他们的服务器端 – Askanison4
在CORS方案的情况下,你将需要添加withCredentials属性集在RequestOptions中为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});
}
谢谢。现在用最新的角度版本。它甚至可以在没有'withCredentials'设置的情况下工作,默认情况下它被设置为true。不需要定义它。 –
Cookies是自动追加请求。你为什么还想把它添加到标题中? –
@JánHalaša我也不太清楚这个问题的那一部分。我在想,也许在头文件做什么和cookies做什么之间存在一些混淆。 – Askanison4