【发布时间】:2017-06-12 05:32:18
【问题描述】:
环顾四周后,我想确定自己做得对,但我开始怀疑,最糟糕的是:我已经没有选择/想法了。
所以我使用 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-CSRF-Token 替换X-CSRFToken,但请求被阻止到chrome“选项”并且似乎没有正确发送:
Request header field x-csrf-token is not allowed by Access-Control-Allow-Headers in preflight response.
但我仍然得到我一直在阅读的错误:
CSRF 验证失败。请求中止。 失败原因: CSRF cookie 未设置。
呃。
我在这里错过了什么?
在我看来,我已经尝试过各种装饰器,即使是这样:
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 根本没有向我的客户端渲染模板。
【问题讨论】:
标签: javascript django post csrf fetch