2015-04-28 162 views
0

我想測試一些AJAX請求到我的Django站點,但服務器不認爲來自我的測試工具的請求是AJAX請求。我需要設置什麼HTTP頭?爲Django設置AJAX請求標頭

服務器代碼有這樣一個測試:

# in myapp/ajax.py 
def my_request(request, some_id): 
    if request.is_ajax(): 
     return json.dumps([some_id, 'processed for AJAX']) 

    # some other processing, or an error 

我使用Postman送我的AJAX請求,我已經學會了Accept頭設置爲application/json,但什麼頭做我設置以表明這是一個AJAX請求?

在Django的代碼,我發現了測試方法:

def is_ajax(self): 
    return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' 

當我HTTP_X_REQUESTED_WITH頭設置爲XMLHttpRequest,測試仍然失敗。

回答

4

當我打開Chrome開發人員工具時,發現常規的AJAX請求包含標頭X-Requested-With,設置爲XMLHttpRequest。在郵遞員請求中添加該郵件頭使其工作。這只是一個稍微不同的名字。

如果您正在進行修改數據的AJAX請求,則需要切換至發出POST請求。這會使Django的cross-site request forgery工具發揮作用,因此您需要從其他表單的隱藏字段複製CSRF令牌,然後在測試AJAX請求時將其粘貼到X-CSRFToken標頭中。

0

任何時候我通過Django發送Ajax數據,我總是把它放在頂部。

// django ajax request info 
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]); 
      // Does this cookie string begin with the name we want? 
      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) { 
    // these HTTP methods do not require CSRF protection 
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); 
} 
function sameOrigin(url) { 
    // test that a given url is a same-origin URL 
    // url could be relative or scheme relative or absolute 
    var host = document.location.host; // host + port 
    var protocol = document.location.protocol; 
    var sr_origin = '//' + host; 
    var origin = protocol + sr_origin; 
    // Allow absolute or scheme relative URLs to same origin 
    return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || 
     (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') || 
     // or any other URL that isn't scheme relative or absolute i.e relative. 
     !(/^(\/\/|http:|https:).*/.test(url)); 
} 

$.ajaxSetup({ 
    beforeSend: function(xhr, settings) { 
     if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) { 
      // Send the token to same-origin, relative URLs only. 
      // Send the token only if the method warrants CSRF protection 
      // Using the CSRFToken value acquired earlier 
      xhr.setRequestHeader("X-CSRFToken", csrftoken); 
     } 
    } 
}); 
+0

感謝您的提醒。 [Django文檔](https://docs.djangoproject.com/en/1.8/ref/csrf/#ajax)也涵蓋了這一點。 –