環顧四周後,我想確保我做的是正確的,但我開始懷疑和最壞:我跑出的選擇/想法。Django作爲API + ReactJS - Redux:POST請求與CSRF令牌,但仍然響應CSRF令牌未設置
因此,我使用django作爲API(我只獲取某些資源的請求),除了基本類視圖中的一個POST方法,以允許我的用戶下載文件。
問題是,Django期望我的POST上的CSRF令牌。
所以,這裏是我從我的reactjs做:
export function sendData(endpoint, req, data) {
return dispatch => {
dispatch(requestData(data));
let csrfToken = Cookies.get('csrftoken');
return fetch(endpoint, {
method: req,
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken,
},
body: JSON.stringify(data),
})
.then(checkStatus)
.then(reponse => {
console.log("Success!");
}).catch(err => {
err.response.json().then((json) =>{
let { Errors, Result } = json;
console.log('request failed: ', Errors, " ", Result);
});
});
};
};
正如您所看到的,我正在使用'whatwg-fetch'庫。 我試圖取代X-CSRFToken
通過X-CSRF-Token
但請求被阻止的鍍鉻「選項」似乎並沒有被正確發送: Request header field x-csrf-token is not allowed by Access-Control-Allow-Headers in preflight response.
但我仍然得到我一直在閱讀有關的錯誤無處不在:
CSRF驗證失敗。請求中止。 給出失敗的原因: CSRF cookie未設置。
Urgh。
我在這裏錯過了什麼?
在我看來,我已經試過各種裝飾甚至這樣的:
class DownloadAssetsView(ViewUrlMixin, ListView):
@csrf_exempt
def post(self, request, *args, **kwargs):
print(request)
return HttpResponse("coucou", status=200, content_type='application/json')
但我不能讓它工作..
PS:Django的沒有模板渲染到我的客戶端,完全可以。
你是對的,它不會工作,如果它不在同一個域上 –
你的問題解決了? –
是的!發送請求塊csrf,如果它在一個跨域... –