首页 文章

在Django项目中基于CSRF令牌AJAX的帖子

提问于
浏览
1

所以我发现了错误,它出现在我的HTML中 . 我刚刚添加 {% csrf_token %} 并且它有效:)感谢助手们!

(我在第一个答案中使用了给我的JS片段,但我仍然得到403 Forbidden错误!)我可能做错了什么?

我最近学习了JS并尝试了以下用于AJAX POST的JS代码,但是我收到403错误 . 做了一些进一步的研究,发现我需要传递一个CSRF令牌 . 我在网上经历了很多教程,但我能找到的唯一解决方案是JQuery,我不知道该语法是如何工作的 . 我需要知道如何通过基于Javascript AJAX的django项目的帖子传递CSRF令牌 . 我的代码是;

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');

this is the error I receive when I clicked on the button mentioned in my code to send some data

2 回答

  • 2

    你需要打电话:

    xhr.setRequestHeader("X-CSRFToken", csrftoken);
    

    当您准备 xhr 请求时 . (在您的示例中 xhr 被命名为 http

    你可以从cookie中获取 csrftoken ,但为了做到这一点,你需要实现一个 getCookie 函数 .

    像这样的东西应该做的伎俩:

    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');
    

    更新

    在你的代码中,这应该是这样的:

    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
    }
    
  • 0

    将这段代码添加到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'));
    }
    

    基本上,您需要将CSRF令牌添加到标头中 . 我找不到我发现这段代码的链接,如果有人知道会很棒的话 .

相关问题