【问题标题】:Django - Ajax request on mobile giving 403 forbidden even when CSRF token is setDjango - 即使设置了 CSRF 令牌,移动设备上的 Ajax 请求也会禁止 403
【发布时间】:2015-12-30 05:05:29
【问题描述】:

我无法在移动平台上测试我使用 django 开发的网站。我设置了我的服务器,以便它使用 javascript 在滚动时从 django 视图中使用 ajax 连续加载帖子。

当我从命令行运行我的服务器并在桌面浏览器上对其进行测试时,该服务运行良好,并且我的帖子持续加载,没有任何 403 禁止错误。但是,当我尝试在手机上对其进行测试时,我可以在服务器的命令输出中看到一个请求已获得 403 禁止响应。

我不确定是什么原因造成的,因为我已经考虑到在进行 ajax 调用之前需要加载 csrf 令牌。

这是我用来加载我的 csrf 令牌的代码。

$(document).ready(function () {
  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]);
              if (cookie.substring(0, name.length + 1) == (name + '=')) {
                  cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                  break;
              }
          }
      }
      return cookieValue;
  }
  var csrftoken = getCookie('csrftoken');
  function csrfSafeMethod(method) {
      return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }
  $.ajaxSetup({
      beforeSend: function(xhr, settings) {
          if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
              xhr.setRequestHeader("X-CSRFToken", csrftoken);
          }
      }
  });

});

这是通过ajax连续调用的视图代码。

# Get a post item
def get_posts (request):
    # Catch any errors
    try:
        # Request for home post
        if request.POST['type'] == 'home':
            # Post index to fetch
            index = int(request.POST['index'])
            # Fetch the post of the specified index
            posts = HomePost.objects.all()
            # Specified index does not exist
            if index >= len(posts):
                # 400 client error response
                return HttpResponse(status='400')
            # Template the post into an html string, cut off './' from image url
            post_html = render_to_string('home_post.html', {'image': str(posts[index].image)[2:], 'body': posts[index].body});
            # Return the templated post html
            return HttpResponse(post_html)
    # Error while parsing
    except:
        # 500 internal server error response
        return HttpResponse(status='500')

编辑:

我进一步测试了哪些特定浏览器会导致同样的问题,我得出的结论是 chrome 桌面是唯一没有这个问题的浏览器。

【问题讨论】:

    标签: jquery ajax django http-status-code-403


    【解决方案1】:

    使用@ensure_csrf_cookie 装饰器。

    来自docs

    页面使用 AJAX,没有任何 HTML 表单¶

    一个页面通过 AJAX 发出一个 POST 请求,并且该页面没有一个带有 csrf_token 的 HTML >表单,这会导致所需的 CSRF cookie 被发送。

    解决方案:在发送页面的视图上使用 ensure_csrf_cookie()。

    【讨论】:

      猜你喜欢
      • 2021-06-28
      • 2018-06-30
      • 2017-05-16
      • 2016-05-08
      • 2015-07-30
      • 2016-06-22
      • 2019-05-02
      • 2020-04-20
      • 2021-10-08
      相关资源
      最近更新 更多