Django CSRF 403

不打扰是莪最后的温柔 提交于 2019-12-02 12:37:53

问题


Getting a CSRF 403. The console.log statements below confirm that I'm grabbing the token. I'm submitting the request to the same domain on my local server.

  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:


not sure if this will help you. I had a similar problem. And fixed it by making a beforeSend functions that's add the X-CSRFToken

$.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!");
  }
})


来源:https://stackoverflow.com/questions/24663554/django-csrf-403

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!