未在 Angular 客户端上设置 Cookie

noP*_*oPE 8 django cookies angular

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

我有一个 angular 前端,它在 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);
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*vid 8

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

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

    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 => {
Run Code Online (Sandbox Code Playgroud)