我有一个后端服务器在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。
有什么建议吗?
编辑:我发现这个问题在别处。
检查https://github.com/ottoyiu/django-cors-headers –
@ PiyushS.Wanare我已经在使用django-cors-headers,但现在我已经使用CORS_ALLOW_HEADERS/METHODS,CSRF_TRUSTED_ORIGINS和CORS_ALLOW_CREDENTIALS,但它仍然不起作用,我得到相同的错误信息。 – dnmh
你发现问题在别处?你可以向我们指出这些信息还是关闭这个问题? – waterproof