Django CSRF 403

时间:2014-07-09 20:49:54

标签: django csrf django-csrf

获取CSRF 403.下面的console.log语句确认我正在抓取令牌。我将请求提交到本地服务器上的同一域。

  internal.csrfToken = $.cookie('csrftoken');

  internal.csrfSafeMethod = function(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    };

  $.ajaxSetup({
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
      console.log("ajaxSetup");
      console.log(internal.csrfToken);
      if (!internal.csrfSafeMethod(settings.type)) {
        console.log("Settings type");
        xhr.setRequestHeader("X-CSRFToken", internal.csrftoken);
      }
    }
  });

  external.submitPayment = function (app_id, charge_now_amount, stripe_plan_id) {
    // Submit a payment to the server and handle any errors.

    $.ajax({
      url: URLS.postPayment,
      type: 'POST',
      data: {
        'app_id': STRIPE_CONFIG.app.id,
        'amount': charge_now_amount,
        'stripe_plan_id': stripe_plan_id
      },
      dataType: 'json',
      success: function(response) {
        alert("Success!");
      },
      error: function(jqXHR, textStatus, errorThrown ) {
        alert("Error!");
      }
    });

  };

1 个答案:

答案 0 :(得分:0)

不确定这是否会对您有所帮助。我遇到了类似的问题。并通过制作一个添加X-CSRFToken

的beforeSend函数来修复它
$.ajax({
  url: url,
  data: JSON.stringify({'name': value }),
  type: 'POST',
  dataType: 'json',
  beforeSend: function (jqXHR, settings) {
    jqXHR.setRequestHeader('X-CSRFToken', $('input[name=csrfmiddlewaretoken]').val());
  },
  success: function(response) {
    alert("Success!");
  }
})