2017-02-13 64 views
0

我有一個後端服務器在localhost:8000和一個前端服務器在localhost:3000。後端是Django,我安裝了corsheaders軟件包,並且沒有問題地發出GET請求。當我打開我的網站時,第一個GET請求成功設置了CSRF令牌(我可以在開發工具中看到cookie)。Django CSRF跨站點AJAX問題

我有這個settings.py中:

CORS_ORIGIN_WHITELIST = (
    'localhost:3000' 
) 

CORS_ALLOW_METHODS = (
    'DELETE', 
    'GET', 
    'OPTIONS', 
    'PATCH', 
    'POST', 
    'PUT' 
) 

CORS_ALLOW_HEADERS = (
    'accept', 
    'accept-encoding', 
    'authorization', 
    'content-type', 
    'dnt', 
    'origin', 
    'user-agent', 
    'x-csrftoken', 
    'x-requested-with', 
) 

CSRF_TRUSTED_ORIGINS = (
    'localhost:3000', 
) 

CORS_ALLOW_CREDENTIALS = True 

現在我想做一個POST請求,我不斷地由服務器拒絕了:

403 - Forbidden (CSRF cookie not set.): /myapp/myview/ 

,這是什麼我的JS看起來像︰

let csrftoken = utils.getCookie('csrftoken'); // logged this on the console, the token is really here 

jQuery.ajaxSetup({ 
    beforeSend: function(xhr, settings) { 
    xhr.setRequestHeader("X-CSRFToken", csrftoken); 
    } 
}); // this might be wrong - I did read it is used only if it's not cross site, but I still gave it a try 

jQuery.ajax({ 
    url: url, 
    type: 'POST', 
    data: {attr: value, csrfmiddlewaretoken: csrftoken} 
})... 

我只試過與AJAX數據csrfmiddlewaretoken。我只嘗試設置請求標題。我已經嘗試了兩種。仍然沒有運氣。我明顯失去了一些東西;我從來沒有嘗試過在各個站點上使用Django進行POST。

有什麼建議嗎?

編輯:我發現這個問題在別處。

+0

檢查https://github.com/ottoyiu/django-cors-headers –

+0

@ PiyushS.Wanare我已經在使用django-cors-headers,但現在我已經使用CORS_ALLOW_HEADERS/METHODS,CSRF_TRUSTED_ORIGINS和CORS_ALLOW_CREDENTIALS,但它仍然不起作用,我得到相同的錯誤信息。 – dnmh

+0

你發現問題在別處?你可以向我們指出這些信息還是關閉這個問題? – waterproof

回答

0

嘗試將XSRF標記放入Ajax請求的標題中。

$.ajax({ 
     url : urlToCall, // the endpoint 
     type : "POST", // http method 
     headers: { "X-CSRFToken": "your token here" }, 
     success : function(response) { 
      console.log('success', response); 
       }, 
      error : function(xhr,errmsg,err) { 
       console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console 
      } 
    }); 
+0

不,現在試過: -/ – dnmh

0

我能夠做到這一點的:

$.ajax({ 
    url : urlToCall, // the endpoint 
    type : "POST", // http method 
    data : { 
     csrfmiddlewaretoken: "Your token", 
     data... 
    }, 

    success : function(response) { 
     console.log('success', response); 
      }, 
     error : function(xhr,errmsg,err) { 
      console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console 
     } 
}); 

希望它能幫助!

+0

不,它基本上和我發佈的問題中的例子一樣。 – dnmh