django - 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 进行身份验证。
解决方案
您正在尝试设置跨域 cookie,这不会立即起作用。有几个步骤可以做到这一点。
withCredentials: true
从角度发出身份验证请求时设置this.http.post<any>('http://localhost:8000/auth/login/', this.LoginForm, { observe: 'response', withCredentials: true })
配置您的服务器以返回以下 CORS 标头:
Access-Control-Allow-Credentials: true
和Access-Control-Allow-Origin: http://localhost:4200
笔记
您设置的 cookie 之一是HttpOnly
. 因此,您无法从 Javascript 访问它(请参阅文档)。
无论如何,您可能不需要使用 JS 访问 cookie。如果您只想在下一个 API 请求中发送 cookie,只需传递withCredentials: true
给HttpClient
其他 api 调用
this.http.get('http://localhost:8000/path/to/get/resource',
{ withCredentials: true }).subscribe(response => {
推荐阅读
- oauth-2.0 - 无法让 Linkedin 从 socialActions v2 端点返回数据
- java - 在java游戏中为多个实体设置方向的问题
- scala - 获取 Scala 类对象中具有值的所有公共字段
- jquery - 带有 JQuery 的下拉 json 数据显示“未定义”结果
- python - python命令行程序作为字符串抛出错误传入
- .net - WPF 更改 ItemContainerStyle 但保留引用的基本样式
- python - 从 Python 中的函数返回一个值并将其绘制在热图上
- c# - C# 引用外部 DLL 中的方法返回错误
- python - 具有多个条件的 SqlAlchemy 案例
- excel - 如何使用独立的标识符列表识别字符串源