2017-02-17 30 views
0

我有以下情况。从后端发送的Cookie未在前端设置

第一部分:

  • 本地主机:3000前端(反应)
  • 本地主机:8000后端(Django的)
  • 我做一个成功的跨域GET(我使用django- CORS报头封装)响应头的

部分:

Set-Cookie: csrftoken=token; expires=Fri, 16-Feb-2018 10:56:00 GMT; Max-Age=31449600; Path=/ 
  • cookie csrftoken没有在浏览器中设置(如果我是正确的,这是由于浏览器忽略来自不同域的cookie),尽管我已经设置为允许第三方cookie和网站数据(在Chrome的设置)
  • POST失败,因为没有设置CSRF饼干

第二部分:

  • 我设置cookie手动
  • 一切都运行完美

这是我的Ajax请求:

jQuery.ajaxSetup({ 
    beforeSend: function(xhr, settings) { 
    xhr.setRequestHeader("X-CSRFToken", csrftoken); 
    } 
}); 

jQuery.ajax({ 
    url: url, 
    type: 'POST', 
    data: {attr: value, csrfmiddlewaretoken: csrftoken}, 
    crossDomain: true, 
    xhrFields: { 
    withCredentials: true 
    } 
}) 

任何初始GET后读取cookie并设置它在浏览器呢?

回答

1

我最近有一个类似的问题,使用Django和角2,我有一个django-cors-headers配置的问题。

你的django-cors-headers是什么? 您无法同时设置全部允许和允许凭据。

这是不允许的:

CORS_ORIGIN_ALLOW_ALL = True 
CORS_ALLOW_CREDENTIALS = True 

使用,而不是:

CORS_ALLOW_CREDENTIALS = True 
CORS_ORIGIN_WHITELIST = (
    'localhost:3000', 
    '127.0.0.1:3000' 
) 

Set-Cookie response header not working using Angular 2 + django-rest-framework

+0

我CORS_ALLOW_CREDENTIALS = True和CORS_ORIGIN_WHITELIST =( '本地主机:3000',“127.0.0.1: 3000'),但没有帮助。 – dnmh

+1

啊,我明白了......我没有在我的阿贾克斯电话:xhrFields:{ withCredentials:true } – dnmh