[英]Set Django CSRF_TOKEN with yui, but console says 'django.request Forbidden (CSRF token missing or incorrect.)'
I use this code in html: 我在html中使用以下代码:
<script>
YUI().use('node', function(Y){
var token = Y.Node.create("{% csrf_token %}");
YUI.Env.CSRF_TOKEN = token._node.firstChild.getAttribute('value');;
});
</script>
And I use some javascript code to send POST method: 我使用一些JavaScript代码发送POST方法:
Y.io('http://10.0.3.71/dashboard/send_t2_data', {
method: 'POST',
data: {'name':'123456'},
headers: {
'Content-Type': 'application/json',
},
on: {
success: function(id, response) {
},
failure: function(id, response) {
}
}
});
But the console says django.request Forbidden (CSRF token missing or incorrect.): /dashboard/send_t2_data
when I submit all data. 但是控制台说django.request Forbidden (CSRF token missing or incorrect.): /dashboard/send_t2_data
当我提交所有数据时。
I follow by the official document to edit YUI.Env.CSRF_TOKEN. 我遵循官方文档来编辑YUI.Env.CSRF_TOKEN。 But it seems that there is something wrong about my code. 但是似乎我的代码有问题。 Why do I configure the environment variable named YUI.Env.CSRF_TOKEN
but it does not effective? 为什么要配置名为YUI.Env.CSRF_TOKEN
的环境变量,但是它无效?
Could someone helps me? 有人可以帮我吗? Thanks a lot! 非常感谢!
I'm not a YUI specialist but it seems you've forgetten the header X-CSRFToken
with the csrftoken
cookie. 我不是YUI专家,但似乎您忘记了带有csrftoken
cookie的标头X-CSRFToken
。
So get the csrftoken
cookie dans set the request header X-CSRFToken
with the value. 因此,获取csrftoken
cookie dans将请求标题X-CSRFToken
设置为该值。 In pure javascript it gave (copy/paste from a project of mine): 用纯JavaScript给出(从我的项目中复制/粘贴):
var xhr = new XMLHttpResquest();
xhr.open('POST', YOUR-URL, YOU-DATA-AS-STRING);
xhr.setRequestHeader("X-CSRFToken", getCSRFCookie());
xhr.send(null);
If I understand your code : 如果我了解您的代码:
Y.io('http://10.0.3.71/dashboard/send_t2_data', {
method: 'POST',
data: {'name':'123456'},
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getcookie('csrftoken')
},
on: {
success: function(id, response) {
},
failure: function(id, response) {
}
}
});
where the function getcookie('csrftoken')
get the cookie named csrftoken
函数getcookie('csrftoken')
获取名为csrftoken
的cookie
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.