I use this code in 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:
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.
I follow by the official document to edit 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?
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.
So get the csrftoken
cookie dans set the request header X-CSRFToken
with the value. In pure javascript it gave (copy/paste from a project of mine):
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