pat*_*ick 5 javascript django json django-csrf
我正在尝试使用 csrf 令牌向我的 Django 应用程序发送 JSON 请求,但我不知道如何操作。我已将令牌放入可以引用的变量中,但我不知道如何使用 fetch 通过 JSON 请求发送它。我已添加'csrfmiddlewaretoken': csrftoken到正文的 JSON.stringify 部分,但仍然收到错误消息 403 Forbidden。有人可以帮我解决这个问题吗?谢谢你!(抱歉代码上有奇怪的缩进)
JavaScript 文件:
fetch('/update', {
method: 'PUT',
body: JSON.stringify({
'csrfmiddlewaretoken': csrftoken,
'liked': true,
'post_id': parseInt(button.dataset.post_id)
})
})
Run Code Online (Sandbox Code Playgroud)
视图.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)
Run Code Online (Sandbox Code Playgroud)
首先要获取csrf可以使用以下代码
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// 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;
Run Code Online (Sandbox Code Playgroud)
}
现在我们已经获得了 CSRF 令牌,请将这行代码添加到 fetch 的标头中
'X-CSRFToken':csrftoken,
Run Code Online (Sandbox Code Playgroud)