我试图用csrf令牌向我的Django应用程序发送JSON请求,但我不知道如何发送。 我已经将令牌放入一个可以引用的变量中,但我不知道如何通过带有FETCH的JSON请求发送它。 我已经将'csrfMiddleWareToken':csrfToken
添加到主体的json.stringify部分中,但是我仍然收到一个错误,说403是禁止的。 谁能帮帮我吗? 谢谢! (对不起代码上的怪异缩进)
Javascript文件:
fetch('/update', {
method: 'PUT',
body: JSON.stringify({
'csrfmiddlewaretoken': csrftoken,
'liked': true,
'post_id': parseInt(button.dataset.post_id)
})
})
views.py:
data = json.loads(request.body)
try:
content = data.get('content')
except:
JsonResponse({'error': 'content required'}, status=400)
try:
id = data.get('id')
post = Post.objects.get(id=id)
except:
JsonResponse({'error': 'post not found'}, status=400)
if request.user == post.user:
post.content = content
post.save()
return JsonResponse({'message': f'received: {content}'})
return JsonResponse({'error': "can't edit this user's posts"}, status=403)
首先,要获得csrf,可以使用以下代码
从此链接获取代码单击me1
现在我们得到了csrf,将这行代码添加到fetch的头中
“X-CSRFToken”:CSRFToken,
首先,从Andrea和Gabcvit,一些代码片断将非常赞赏。
编辑Farhan的回答:您需要手动检索csrf令牌,因为javascript中没有默认设置。 您可以通过以下方式完成此操作:
import jQuery from 'jquery'; // important dependency
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
let cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
let cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
如果React没有收到Django的csrf令牌(在我的情况下就发生了),您需要在视图上方添加以下代码:
@method_decorator(ensure_csrf_cookie, name='dispatch')
class UserLoginView(View):
# ...
如果您需要更多的帮助,这篇MDN文章将帮助您。