我是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