2017-02-13 97 views
0

我有一个后端服务器在localhost:8000和一个前端服务器在localhost:3000。后端是Django,我安装了corsheaders软件包,并且没有问题地发出GET请求。当我打开我的网站时,第一个GET请求成功设置了CSRF令牌(我可以在开发工具中看到cookie)。Django CSRF跨站点AJAX问题

我有这个settings.py中:

CORS_ORIGIN_WHITELIST = (
    'localhost:3000' 
) 

CORS_ALLOW_METHODS = (
    'DELETE', 
    'GET', 
    'OPTIONS', 
    'PATCH', 
    'POST', 
    'PUT' 
) 

CORS_ALLOW_HEADERS = (
    'accept', 
    'accept-encoding', 
    'authorization', 
    'content-type', 
    'dnt', 
    'origin', 
    'user-agent', 
    'x-csrftoken', 
    'x-requested-with', 
) 

CSRF_TRUSTED_ORIGINS = (
    'localhost:3000', 
) 

CORS_ALLOW_CREDENTIALS = True 

现在我想做一个POST请求,我不断地由服务器拒绝了:

403 - Forbidden (CSRF cookie not set.): /myapp/myview/ 

,这是什么我的JS看起来像︰

let csrftoken = utils.getCookie('csrftoken'); // logged this on the console, the token is really here 

jQuery.ajaxSetup({ 
    beforeSend: function(xhr, settings) { 
    xhr.setRequestHeader("X-CSRFToken", csrftoken); 
    } 
}); // this might be wrong - I did read it is used only if it's not cross site, but I still gave it a try 

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

我只试过与AJAX数据csrfmiddlewaretoken。我只尝试设置请求标题。我已经尝试了两种。仍然没有运气。我明显失去了一些东西;我从来没有尝试过在各个站点上使用Django进行POST。

有什么建议吗?

编辑:我发现这个问题在别处。

+0

检查https://github.com/ottoyiu/django-cors-headers –

+0

@ PiyushS.Wanare我已经在使用django-cors-headers,但现在我已经使用CORS_ALLOW_HEADERS/METHODS,CSRF_TRUSTED_ORIGINS和CORS_ALLOW_CREDENTIALS,但它仍然不起作用,我得到相同的错误信息。 – dnmh

+0

你发现问题在别处?你可以向我们指出这些信息还是关闭这个问题? – waterproof

回答

0

尝试将XSRF标记放入Ajax请求的标题中。

$.ajax({ 
     url : urlToCall, // the endpoint 
     type : "POST", // http method 
     headers: { "X-CSRFToken": "your token here" }, 
     success : function(response) { 
      console.log('success', response); 
       }, 
      error : function(xhr,errmsg,err) { 
       console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console 
      } 
    }); 
+0

不,现在试过: -/ – dnmh

0

我能够做到这一点的:

$.ajax({ 
    url : urlToCall, // the endpoint 
    type : "POST", // http method 
    data : { 
     csrfmiddlewaretoken: "Your token", 
     data... 
    }, 

    success : function(response) { 
     console.log('success', response); 
      }, 
     error : function(xhr,errmsg,err) { 
      console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console 
     } 
}); 

希望它能帮助!

+0

不,它基本上和我发布的问题中的例子一样。 – dnmh