实际上,我们的后端使用请求头中的Cookie对请求进行身份验证.我知道如果我设置一个标题"Cookie"它会拒绝的.那么,有没有办法把Cookie送到后端呢?
实际上,我们的后端使用请求头中的Cookie对请求进行身份验证.我知道如果我设置一个标题"Cookie"它会拒绝的.那么,有没有办法把Cookie送到后端呢?
我猜有一个阶段,你要求服务器验证你的身份.接下来(如果身份验证成功),服务器将在响应中返回一个cookie.浏览器将存储此cookie,并在每次通话时再次发送.
也就是说,在跨域请求(CORS)的情况下,您需要将XHR的withCredentials
设置为true
,以使浏览器在您的请求中添加cookie.
为了使用Angular2实现这一点,我们需要扩展BrowserXhr
类,如下所述:
@Injectable()
export class CustomBrowserXhr extends BrowserXhr {
constructor() {}
build(): any {
let xhr = super.build();
xhr.withCredentials = true;
return <any>(xhr);
}
}
并用扩展的
bootstrap(AppComponent, [
HTTP_PROVIDERS,
provide(BrowserXhr, { useClass: CustomBrowserXhr })
]);
有关更多详细信息,请参阅此问题:
Edit (following the 100's comment)
从RC2中,您可以直接在请求配置中使用withCredentials
属性,如下所述:
this.http.get('http://...', { withCredentials: true })
Edit (following the [maxou] comment)
记住要包括withCredentials:true on every request.