cookie在使用Django和CORS的AngularJS应用程序中消失 [英] cookie disappeared in AngularJS app using Django and CORS

查看:305
本文介绍了cookie在使用Django和CORS的AngularJS应用程序中消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django Rest Framework和Django CORS Headers作为后端API来构建AngularJS应用程序。

I'm building an AngularJS app with Django Rest Framework and Django CORS Headers as backend API.

一切正常,直到今天。突然, csrfcookie sessionid cookie 已停止在Chrome中显示。

Everything was working fine until today. Suddenly the csrfcookie and sessionid cookie stopped showing up in Chrome.

我看到API使用 csrfcookie 回应我。 Chrome不会在开发工具中显示,但我在 chrome:// settings / cookies 中看到。

I see the API responding to me with the csrfcookie. Chrome doesn't show it in dev tools, however I see it in chrome://settings/cookies.

AngularJS

$httpProvider.defaults.useXDomain = true;
$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$http({withCredentials: true, ...})

Django API

CORS_ALLOW_CREDENTIALS = True

CORS_ALLOW_HEADERS = (
    'x-requested-with',
    'content-type',
    'accept',
    'origin',
    'authorization',
    'X-CSRFToken'
)


推荐答案

相当简单,但并不总是非常容易注意到,因为没有来自API或客户端的错误消息。

Ok so the answer to this issue is quite simple but not always very easy to notice since there are no error messages from the API, nor the client.

上述问题是我居住在 domain.com 在我的浏览器,但我的要求是对API是www.domain.com:8000 www.domain.com domain.com 是我的API中允许的起点。

The problem above is that I reside on domain.com in my browser, but my request is towards the API is to "www.domain.com:8000". Both www.domain.com and domain.com are allowed origins in my API.

这里的结论是如果我位于 domain.com ,那么我需要向 domain.com:8000 发出我的API请求。但是,如果我的浏览器位于 www.domain.com ,那么我需要向 www.domain.com:8000 发出我的API请求。

Conclusion here is that if I reside on domain.com then I need to make my API request towards domain.com:8000. But if reside on www.domain.com in my browser, then I need to make my API request towards www.domain.com:8000.

下面是一个工作示例:

Cookie现在看起来不错!

Cookies now appear fine!

节省几个小时的沮丧:)

I hope this helps anyone, saving a few hours of frustration :)

更新:
在Django设置文件中启用以下设置也将解决问题。使用它们让您驻留在浏览器中的不同子域,并且Cookie将返回域.domain.com

Update: Enabling the following settings in the Django settings file will also solve the problem. Using them let's you reside on different subdomains in your browser, and the cookies will return for domain ".domain.com"

https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-域
https:// docs.djangoproject.com/en/dev/ref/settings/#session-cookie-domain

感谢irc.freenode.net上的apollo,# django的更新答案。

Thanks to apollo on irc.freenode.net, #django for the updated answer.

这篇关于cookie在使用Django和CORS的AngularJS应用程序中消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆