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 进行身份验证。
您正在尝试设置跨域 cookie,这不会立即起作用。要做到这一点,需要遵循几个步骤。
withCredentials: true
从 angular 发出身份验证请求时设置
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 => {
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4204 次 |
最近记录: |