简体   繁体   English

除了ajax request + django中缺少csrf令牌外,是否还有其他原因会导致403错误?

[英]Are there any other reason which can cause 403 error except absence of csrf token in ajax request + django?

The main reason of django + ajax 403 error is absence of csrf token, but in my case it's present and almost the same ajax function works fine. django + ajax 403错误的主要原因是缺少csrf令牌,但就我而言,它存在并且几乎相同的ajax函数都可以正常工作。 I'll also attach backend view function handling the response using djangorestframework. 我还将附加使用djangorestframework处理响应的后端视图函数。

  $.ajax({
    url: '/authsteptwo/',
    type:'POST',
    dataType: 'json',
    data: { phone_number : phone_number, email : email, csrfmiddlewaretoken: "{{ csrf_token }}" },
    success: function () {

      // alert('succes');
      setTimeout(
  function() 
  {
      alert('fine');
  }, 0);

    },
    error : function() {


        alert('fck');
    }


  })

view 视图

@api_view(['POST', ])
def auth_step_two(request):
    if request.method == 'POST':
        phone_number = request.data['phone_number']
        email = request.data['email']
        # user = request.user.UserProfile
        # user.email = email
        # user.phone_number = phone_number
        # user.save()
    else:
        print("WTF")
    return Response(request.data)

console: 安慰:

Failed to load resource: the server responded with a status of 403 (FORBIDDEN)

Are there any other reason which can cause 403 error ? 还有其他原因会导致403错误吗?

EDIT: I tried just to call ajax function out of all condition in the beggingign of the page, just after and it worked. 编辑:我只是试图从页面的乞讨条件中的所有条件中调用ajax函数,然后就可以了。 But calling the same function onclick(without real data, so it's not related) fails wth 403 or also falls on jQuery click event. 但是调用相同的函数onclick(没有真实数据,因此不相关)在403上失败,或者也发生在jQuery click事件上。 Very weird. 很奇怪。 Any suggestions what could it be? 有什么建议吗?

EDIT: Oh, I figured out that no ajax function in fact working after first ajax auth call executed. 编辑:哦,我发现执行第一个Ajax身份验证调用后实际上没有Ajax函数起作用。 I attach the code of first call which works and after that nothing works. 我附上了有效的首次通话代码,此后没有任何效果。 Help me understand why? 帮我明白为什么吗?

 $.ajax({
    url: '/authfb/',
    type:'POST',
    dataType: 'json',
    data: {"fb_first_name": fb_first_name, "fb_last_name": fb_last_name, "fb_username": fb_username, "fb_email":fb_email, "fb_id":fb_id, "fb_link":fb_link, csrfmiddlewaretoken: "{{ csrf_token }}" },
    success: function () {

      // alert('succes');
      setTimeout(
  function() 
  {
    $('#hide_group').hide();
    $('#show_group').show();
    $('.loading_white_wall').fadeOut();
    $('.greeting_title_name').html(fb_first_name);
    if(fb_email){

      $(".email_input").prop("value", fb_email);
    }

    else{

        $(".email_input").prop("placeholder", 'E-mail');
    }


  }, 1000);

    },
    error : function(data) {

      $('#hide_group').hide();
      $('#error_group').show();
      $('.loading_white_wall').fadeOut();

    }


  })

And also the exact code of handler, there is much but possible something somehow related, but most likely no much use of it: 以及处理程序的确切代码,有很多但可能有些相关的东西,但很可能没有太多使用:

@api_view(['POST', ])
def authfb(request):
    require_more_data = True
    if request.method == 'POST':
        first_name = request.data['fb_first_name']
        last_name = request.data['fb_last_name']
        fb_username = request.data['fb_username']
        fb_id = int(request.data['fb_id'])
        fb_link = request.data['fb_link']
        username = fb_username.replace(' ', '')
        print(fb_link)
        print (type(fb_id))

        # print(username)
        password = '11442358'
        user = auth.authenticate(username=username, password=password)
        # print(type(username))
        # print(type(password))
        if user is not None:
            auth.login(request, user)
            username = auth.get_user(request).username
            print ('logged in succesfully')
            # user1 = UserProfile.user.objects.get(username=username)
            # if (user1.userprofile.phone_number):
            #     print ("hello")
            # email = auth.get_user(request).UserProfile.email
            # if phone_number and email:
            #     require_more_data = False
        else:
            user = User.objects.create_user(username=username, password=password)
            userprofile = UserProfile.objects.create(user=user, first_name=first_name, last_name=last_name)
            user = auth.authenticate(username=username, password=password)
            auth.login(request, user)
            print (userprofile)
    else:
        print("WTF")
    return Response(request.data)

I found a solution in one of my old projects. 我在一个旧项目中找到了解决方案。 If someone explains why this works and previous is wrong, I'll mark as correct. 如果有人解释为什么这样做有效,而以前的说法是错误的,我会标记为正确。

function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}
var csrftoken = getCookie('csrftoken');
 $.ajaxSetup({
        headers: { "X-CSRFToken": getCookie("csrftoken") }
    });

in ajax call 在ajax电话

    data: {"fb_first_name": fb_first_name,'csrfmiddlewaretoken': getCookie('csrftoken') },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM