【问题标题】:Getting 403 Forbidden error even after providing csrf token即使在提供 csrf 令牌后也出现 403 Forbidden 错误
【发布时间】:2013-04-25 02:40:38
【问题描述】:

以下是我的 Ajax POST 请求

这是在模板上

<script type="text/javascript">
    function submit_vote(){
        callback = function(data){
            alert(data.message);
        };

        $.post("{{request.get_full_path}}vote",{
            "rating" : $('#{{hash_id}}').raty('score')
        }, callback, "json");
    }
</script>

<div class="rating" id="{{hash_id}}" onclick="submit_vote()"></div>

关于视图,这里是它

这是呈现存在 Ajax 脚本的模板的视图

@csrf_protect
def show_rating(request, **kwargs):
    ....
    ....
    return render_to_response("rating.html",
                context,
                context_instance = RequestContext(request))

这是接受 POST 请求的视图

@login_required
@csrf_protect
def submit_vote(request, **kwargs):
    if not request.method == "POST":
        raise Http404

    ...
    ...

    data = {"error" : False, "message" : "Thanks"}
    data = simplejson.dumps(data)
    return HttpResponse(data, mimetype="application/javascript")

在尝试上述代码时,我收到 403 Forbidden Error.. 通过使用 django 文档,我在现有代码中添加了另一个脚本(在顶部)

<script type="text/javascript">
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));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
            // Send the token to same-origin, relative URLs only.
            // Send the token only if the method warrants CSRF protection
            // Using the CSRFToken value acquired earlier
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});
</script>

现在我明白了

Uncaught ReferenceError: csrftoken is not defined 

错误..

如何解决?实际上,我不知道 Ajax 和 Jquery 和 JS.. 只是试图从网络上的教程中构建一个简单的请求!

【问题讨论】:

    标签: jquery ajax django django-csrf


    【解决方案1】:

    您可以在您的帖子请求中发送csrfmiddlewaretoken,它应该会被修复。

    $.post("{{request.get_full_path}}vote",{
            "rating" : $('#{{hash_id}}').raty('score'),
            "csrfmiddlewaretoken": {{csrf_token}},
        }, callback, "json");
    

    您不需要任何其他脚本。

    【讨论】:

      猜你喜欢
      • 2017-07-15
      • 2016-02-13
      • 2018-06-30
      • 1970-01-01
      • 2017-11-02
      • 2021-07-08
      • 2013-12-03
      • 2019-11-29
      • 2015-07-06
      相关资源
      最近更新 更多