如何发送“Cookie"在 Angular2 中所有请求的请求头中? [英] How to send "Cookie" in request header for all the requests in Angular2?

查看:21
本文介绍了如何发送“Cookie"在 Angular2 中所有请求的请求头中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上,我们的后端使用请求标头中的 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:

编辑(按照 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 中所有请求的请求头中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆