[英]CSRF token AJAX based post in a Django Project
So I found out the error and it was in my HTML. 所以我发现了错误,它在我的HTML中。 I just added
{% csrf_token %}
and it worked :) thanks for the assist guys! 我刚刚添加了
{% csrf_token %}
,它的效果很{% csrf_token %}
:)感谢您的协助!
(I used the JS snippet given to me in the first answer but I am still getting a 403 Forbidden error!) what could I be doing wrong?
(我在第一个答案中使用了给我的JS代码段,但仍然收到403 Forbidden错误!)我怎么可能做错了?
I recently learnt JS and tried the following JS code for AJAX POST but I am getting a 403 error. 我最近学习了JS,并尝试了AJAX POST的以下JS代码,但出现403错误。 Did some further research and found that I needed to pass a CSRF token.
做了一些进一步的研究,发现我需要传递一个CSRF令牌。 I have gone through a lot of tutorials online but the only solutions I was able to find were of JQuery and I have no idea how that syntax works.
我已经在线阅读了很多教程,但是我唯一能找到的解决方案是JQuery,而且我不知道该语法如何工作。 I need to know how to pass a CSRF token via Javascript AJAX based post for a django project.
我需要知道如何通过Django项目的基于Javascript AJAX的帖子传递CSRF令牌。 My code is;
我的代码是;
var upvoteBtn = document.querySelector('#upvote');
var downvoteBtn = document.querySelector('#downvote');
upvoteBtn.addEventListener('click', jL);
downvoteBtn.addEventListener('click', cL);
function jL(event) {
document.getElementById("upvote").style.display='none';
document.getElementById("downvote").style.display='none';
var http = new XMLHttpRequest ();
var url = 'entered my url here';
var data = 'title=Post%20Title&body=Body';
var method = 'POST';
http.open(method, url, true);
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
http.setRequestHeader("X-CSRFToken", csrftoken);
http.onreadystatechange = function() {
if (http.readyState === XMLHttpRequest.DONE && http.status === 200){
document.getElementById("first").innerHTML = "this post has been voted";
console.log("upvote given");
}
else if (http.readyState === XMLHttpRequest.DONE && http.status !== 200){
console.log("error!", http.responseText);
}
};
http.send(data);
}
function cL(event){
document.getElementById("upvote").style.display='none';
document.getElementById("downvote").style.display='none';
var http = new XMLHttpRequest ();
var url = 'entered my url here';
var data = 'title=Post%20Title&body=Body';
var method = 'POST';
http.open(method, url, true);
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
http.setRequestHeader("X-CSRFToken", csrftoken);
http.onreadystatechange = function() {
if (http.readyState === XMLHttpRequest.DONE && http.status === 200){
document.getElementById("first").innerHTML = "got downvoted";
console.log("downvoted!");
}
else if (http.readyState === XMLHttpRequest.DONE && http.status !== 200){
console.log("error!", http.responseText);
}
};
http.send(data);
}
//function for CSRF token
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
var csrftoken = getCookie('csrftoken');
You need to call: 您需要致电:
xhr.setRequestHeader("X-CSRFToken", csrftoken);
when you prepare your xhr
request. 当您准备
xhr
请求时。 (in your example xhr
is named http
) (在您的示例中,
xhr
名为http
)
you can get the csrftoken
from the cookie, but in order to do that you need to implement a getCookie
function. 您可以从cookie中获取
csrftoken
,但是为此,您需要实现getCookie
函数。
Something like this should do the trick: 这样的事情应该可以解决问题:
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
var csrftoken = getCookie('csrftoken');
In your code this should look something like this: 在您的代码中,看起来应该像这样:
upvoteBtn.addEventListener('click', jL);
downvoteBtn.addEventListener('click', cL);
//first define your getCookie function
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function jL(event) {
//...
//Then when you prepare you data fetch the token
var csrftoken = getCookie('csrftoken');
http.open(method, url, true);
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
//Now set it
http.setRequestHeader("X-CSRFToken", csrftoken);
//... the rest of your code
}
function cL(event){
//do the same here
}
Add this piece of code into your JS: 将这段代码添加到您的JS中:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = $.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function sameOrigin(url) {
// test that a given url is a same-origin URL
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
// or any other URL that isn't scheme relative or absolute i.e relative.
!(/^(\/\/|http:|https:).*/.test(url));
}
if (!csrfSafeMethod(http.responseType) && sameOrigin(http.responseUrl)) {
http.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
Basically you need to add the CSRF token to the headers. 基本上,您需要将CSRF令牌添加到标头中。 I cannot find the link where I found this piece of code, if anyone knows would be great.
如果有人知道会很棒,那么我找不到在这段代码中找到的链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.