{{csrf_token}}给我403 Forbidden和{%csrf_token%}给我500服务器错误 [英] {{csrf_token}} gives me 403 Forbidden and {%csrf_token%} gives me 500 Server Error

查看:153
本文介绍了{{csrf_token}}给我403 Forbidden和{%csrf_token%}给我500服务器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了这两个基本相同的东西,但是每一个都给了我不同的错误,我不知道哪一个要去。我甚至不知道如何解决这个问题。有人可以看看我的代码,我现在在奋斗两天。



我的html

 < div id ='notificationsLoader'> ; 
< / div>
< script>
$(document).ready(function(){
$(。notification-toggle)。click(function(e){
e.preventDefault();
$ .ajax({
type:POST,
url:{%url'get_notifications_ajax'%},
data:{
csrfmiddlewaretoken:{%csrf_token% },
},
success:function(data){
$(#notificationsLoader)。html('< h3> notifications< / h3>');
$(data.notifications).each(function(){
$(notificationsLoader)。append(this +< br />)
})
控制台。 log(data.notifications);
},
错误:function(rs,e){
console.log(rs);
console.log(e);
}


})
})
})
< / script>

其他html

 < li>< a class =notification-togglehref =#>通知< / a>< / li> 

,通知来自我的python代码

  @login_required 
def get_notifications_ajax(request):
notification = Notification.objects.get(id = id)
notes = []

通知中的笔记:
notes.append(str(note))
data = {
notifications:notes
}
json_data = json .dumps(data)
return HttpResponse(json_data,content_type ='application / json')

还有更多的这个,但我会发布这部分,因为我认为错误(403和500)说我的服务器端是错误的

解决方案

Django Project Documenation


虽然上述方法可以用于AJAX POST请求,但有一些不便之处:您必须记住通过CSRF标记为
POST数据与每个POST请求。因此,有一个
替代方法:在每个XMLHttpRequest上,将自定义的X-CSRFToken
头标设置为CSRF令牌的值。这通常更容易,因为
许多JavaScript框架提供钩子,允许在每个请求上设置
的标题。


所以你可以通过csrftoken值作为 X-CSRFToken 头,可以从cookie中获取(我添加了 getCookie 功能为此需要)。您可以在发送前通过 ajaxSetup 设置ajax请求来轻松实现,请参阅以下代码:

  //源https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#ajax 
函数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 = jQuery.trim(cookies [i]);
//这个cookie字符串是否以我们想要的名字开头?
if(cookie.substring(0,name.length + 1)==(name +'=')){
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}

$(。notification-toggle)。click(function(e){
e.preventDefault();
var token = getCookie(' csrftoken');
$ .ajaxSetup({'headers':{'X-CSRFToken':token}});
// $ .ajax ...

实际上,您可以尝试从以下位置替换您的数据:

  data:{
csrfmiddlewaretoken:{%csrf_token%},
},



  data:{
csrfmiddlewaretoken:$(input [name = csrfmiddlewaretoken] ).val()
},


I read these two are basically same thing, but each one gives me different errors I'm not sure which one to go after. I don't even know how to fix this problem. Can someone please take a look at my code,,I'm struggling with this for two days now.

my html

<div id='notificationsLoader'>
    </div>
<script>
$(document).ready(function(){
  $(".notification-toggle").click(function(e){
    e.preventDefault();
    $.ajax({
      type:"POST",
      url:"{% url 'get_notifications_ajax' %}",
      data: {
        csrfmiddlewaretoken:"{%csrf_token%}",
      },
      success: function(data){
        $("#notificationsLoader").html('<h3>notifications</h3>');
        $(data.notifications).each(function(){
          $("notificationsLoader").append(this + "<br/>")
        })
        console.log(data.notifications);
      },
      error: function(rs, e){
        console.log(rs);
        console.log(e);
      }


    })
  })
})
</script>

the other html

 <li><a class="notification-toggle" href="#">notification</a></li>

and notification is from my python code

@login_required
def get_notifications_ajax(request):
    notification = Notification.objects.get(id=id)
    notes =[]

    for note in notifications:
        notes.append(str(note))
    data={
        "notifications":notes
        }
    json_data = json.dumps(data)
    return HttpResponse(json_data, content_type='application/json')

there's more to this, but I'll post just this part because I think the error(both 403 and 500) is saying my server side is wrong

解决方案

From Django Project Documenation:

While the above method can be used for AJAX POST requests, it has some inconveniences: you have to remember to pass the CSRF token in as POST data with every POST request. For this reason, there is an alternative method: on each XMLHttpRequest, set a custom X-CSRFToken header to the value of the CSRF token. This is often easier, because many javascript frameworks provide hooks that allow headers to be set on every request.

So you can pass csrftoken value as X-CSRFToken header, it could be fetched from cookie ( i've added getCookie function for that needs). You can easily do it by setuping your ajax request with ajaxSetup before sending it, see code below:

// Source https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#ajax    
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 = jQuery.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;
}

$(".notification-toggle").click(function(e){
  e.preventDefault();
  var token = getCookie('csrftoken');
  $.ajaxSetup({'headers': {'X-CSRFToken': token}});
  // $.ajax... 

Altrnatively you can try to replace your data from:

data: {
        csrfmiddlewaretoken:"{%csrf_token%}",
      },

to

data: {
        csrfmiddlewaretoken:$("input[name=csrfmiddlewaretoken]").val()
      },

这篇关于{{csrf_token}}给我403 Forbidden和{%csrf_token%}给我500服务器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆