在 JSON 请求中发送 csrf_token(没有 ajax)
send csrf_token in JSON request (no ajax)
我正在尝试使用 csrf 令牌向我的 Django 应用程序发送 JSON 请求,但我不知道如何操作。我已将令牌放入一个我可以引用的变量中,但我不知道如何通过 JSON 请求使用 fetch 发送它。我已将 '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)
})
})
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可以使用下面的代码
从这里获取代码 link 点击我1
既然我们得到了 csrf ,请将这行代码添加到您 headers 的 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):
# ...
如果您需要更多帮助,this MDN article 会帮助您。
我正在尝试使用 csrf 令牌向我的 Django 应用程序发送 JSON 请求,但我不知道如何操作。我已将令牌放入一个我可以引用的变量中,但我不知道如何通过 JSON 请求使用 fetch 发送它。我已将 '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)
})
})
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可以使用下面的代码
从这里获取代码 link 点击我1
既然我们得到了 csrf ,请将这行代码添加到您 headers 的 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):
# ...
如果您需要更多帮助,this MDN article 会帮助您。