2014-07-09 71 views
1

獲取CSRF 403.下面的console.log語句確認我正在獲取令牌。我正在將請求提交到本地服務器上的同一個域。Django CSRF 403

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

    }; 

回答

0

不知道這是否對您有幫助。我有類似的問題。並通過製作一個beforeSend功能來修復它,這是添加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!"); 
    } 
})