问题描述
实际上,我们的后端使用请求标头中的Cookie对请求进行身份验证.我知道如果设置标题"Cookie",它将拒绝.那么,有没有办法将Cookie发送到后端?
Actually , our backend authenticate the request using Cookie in the request header. I know that it will refuse if I set a header "Cookie". So , is there a way to send a Cookie to the back end ?
推荐答案
我猜您有一个阶段要求服务器对您进行身份验证.此后(如果身份验证成功),服务器将在响应中返回一个cookie.浏览器将存储此cookie并针对每次调用再次发送.
I guess that there is a phase where you ask the server to authenticate you. Following this (and if the authentication is successful), the server will return a cookie in the response. The browser will store this cookie and send it again for each call.
也就是说,对于跨域请求(CORS),您需要将XHR的withCredentials
设置为true
,以使浏览器在您的请求中添加cookie.
That said, in the case of cross domain requests (CORS), you need to set the withCredentials
of XHR to true
to make the browser add cookies in your requests.
要在Angular2中启用此功能,我们需要扩展BrowserXhr
类,如下所述:
To enable this with Angular2, we need to extend the BrowserXhr
class as described below:
@Injectable()
export class CustomBrowserXhr extends BrowserXhr {
constructor() {}
build(): any {
let xhr = super.build();
xhr.withCredentials = true;
return <any>(xhr);
}
}
,并使用扩展名覆盖BrowserXhr
提供程序:
and override the BrowserXhr
provider with the extended:
bootstrap(AppComponent, [
HTTP_PROVIDERS,
provide(BrowserXhr, { useClass: CustomBrowserXhr })
]);
有关更多详细信息,请参见以下问题:
See this questions for more details:
- Set-cookie in response not set for Angular2 post request
- xmlhttprequest and set-cookie & cookie
编辑(遵循 freaker 的评论)
Edit (following the freaker's comment)
在RC2中,您可以直接在请求配置中使用withCredentials
属性,如下所述:
From RC2, you can use the withCredentials
property directly within the request configuration as described below:
this.http.get('http://...', { withCredentials: true })
编辑(在[maxou]条注释之后)
记住要包括withCredentials:对每次请求都为true.
Remember to include withCredentials: true on every request.
这篇关于如何发送"Cookie"在Angular2中所有请求的请求标头中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!