首页 > 解决方案 > Cookie 未在 Angular 客户端上设置

问题描述

我在 django python 中有一个后端应用程序,它在 http://localhost:8000 上提供服务。

我有一个角前端,它在 http://localhost:4200 上提供服务。

我在 django 上禁用了 CORS。在 http://localhost:8000/auth/login/ 上点击登录 api 时,我得到了一个有效的响应以及 Set-Cookie 标头。 在此处输入图像描述

这是我打印cookie的角度代码:

  this.http.post<any>('http://localhost:8000/auth/login/', this.LoginForm, { observe: 'response' }).subscribe(response => {
   console.log("response is ", response);
   var cookies = this.cookieService.getAll();//('cookies');
   console.log("cookies is :", cookies);

它在控制台上打印一个空对象。我该如何进行这项工作?我想使用 cookie 进行身份验证。

标签: djangoangularcookies

解决方案


您正在尝试设置跨域 cookie,这不会立即起作用。有几个步骤可以做到这一点。

  1. withCredentials: true从角度发出身份验证请求时设置

    this.http.post<any>('http://localhost:8000/auth/login/', this.LoginForm, { observe: 'response', withCredentials: true })

  2. 配置您的服务器以返回以下 CORS 标头:Access-Control-Allow-Credentials: trueAccess-Control-Allow-Origin: http://localhost:4200

笔记

您设置的 cookie 之一是HttpOnly. 因此,您无法从 Javascript 访问它(请参阅文档)。

无论如何,您可能不需要使用 JS 访问 cookie。如果您只想在下一个 API 请求中发送 cookie,只需传递withCredentials: trueHttpClient其他 api 调用

this.http.get('http://localhost:8000/path/to/get/resource',
  { withCredentials: true }).subscribe(response => {

推荐阅读