gpt4 book ai didi

django - 未在 Angular 客户端上设置 Cookie

转载 作者:行者123 更新时间:2023-12-04 11:08:32 25 4
gpt4 key购买 nike

我在 django python 中有一个后端应用程序,它在 http://localhost:8000 上提供服务。
我有一个 angular 前端,它在 http://localhost:4200 上提供服务。
我在 Django 上禁用了 CORS。
在 http://localhost:8000/auth/login/上点击登录 api,我得到了有效的响应
以及 Set-Cookie header 。
enter image description here
这是我打印 cookie 的 Angular 代码:

  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 进行身份验证。

最佳答案

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

  • 套装withCredentials: true从 Angular 发出身份验证请求时this.http.post<any>('http://localhost:8000/auth/login/', this.LoginForm, { observe: 'response', withCredentials: true })
  • 配置您的服务器以返回以下 CORS header :Access-Control-Allow-Credentials: trueAccess-Control-Allow-Origin: http://localhost:4200

  • 备注
    您正在设置的 cookie 之一是 HttpOnly .因此,您无法从 Javascript 访问它(请参阅 documentation )。
    无论如何,您可能不需要使用 JS 访问 cookie。如果你只是想在接下来的 API 请求中发送 cookie,只需传递 withCredentials: trueHttpClient其他 API 调用
    this.http.get('http://localhost:8000/path/to/get/resource',
    { withCredentials: true }).subscribe(response => {

    关于django - 未在 Angular 客户端上设置 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62674236/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com