无法在 javascript 提取中设置 Django X-CSRF 令牌
Django X-CSRF token cannot be set in javascript fetch
我正在尝试在 javascript 中生成一个 csrf 令牌,并将其与使用 fetch 的 POST 请求一起使用。
在我的 html 中,我在 head 下有以下脚本标记来生成 csrf 令牌:
<head>
<script type="text/javascript">
var user = '{{request.user}}'
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;
}
var csrftoken = getCookie('csrftoken');
console.log(csrftoken)
</script>
</head>
然后在 body 下,我有以下脚本标记,我在其中检索 csrftoken 变量并将其传递给 'X-CSRFToken' header 在 fetch():
<body>
<script type="text/javascript">
console.log('Hello World')
console.log(csrftoken)
var updateButtons = document.getElementsByClassName('update-cart')
for(i = 0; i < updateButtons.length; i++){
updateButtons[i].addEventListener('click', function(){
var productId = this.dataset.product
var action = this.dataset.action
console.log('productId: ', productId, 'action: ', action)
console.log('user: ', user)
if(user === 'AnonymousUser'){
console.log('Not logged in.')
}else{
updateUserOrder(productId, action)
}
})
}
function updateUserOrder(productId, action){
console.log('User is authenticated. Sending data...')
console.log(csrftoken)
var url = '/update_item/'
fetch(url, {
method: 'POST',
headers: {
'Content-Type':'application/json',
'X-CSRFToken':csrftoken,
},
body: JSON.stringify({'productId': productId, 'action': action})
})
.then((response) => {
return response.json()
})
.then((data) => {
console.log('data: ', data)
})
}
</script>
</body>
所有 console.log() 调用都会显示 csrftoken 变量,但我仍然遇到以下异常:
(index):169 POST http://127.0.0.1:8000/update_item/ 500 (Internal Server Error)
updateUserOrder
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
views.py,
def update_item(request):
data = json.loads(request.data)
product_id = data['productId']
action = data['action']
print('action: ', action)
print('product_id: ', product_id)
customer = request.user.customer
product = Product.objects.get(id=product_id)
order, created = Order.objects.get_or_create(customer=customer, complete=False)
orderitem, created = OrderItem.objects.get_or_create(order=order, product=product)
if action == 'add':
orderitem.quantity += 1
elif action == 'remove':
orderitem.quantity -= 1
orderitem.save()
if orderitem.quantity <= 0:
orderitem.delete()
return JsonResponse('Item was added.', safe=False)
我似乎无法弄清楚这是语法错误还是我设置的 'X-CSRFToken' header 错误。其他类似的答案没有帮助。
已解决。这不是我的 javascript 或其中的 csrftoken 变量的问题。相反,它在我的服务器代码中。
在 views.py 中,我输入了 data = json.loads(request.data)
。不过应该是data = json.loads(request.body)
.
我正在尝试在 javascript 中生成一个 csrf 令牌,并将其与使用 fetch 的 POST 请求一起使用。 在我的 html 中,我在 head 下有以下脚本标记来生成 csrf 令牌:
<head>
<script type="text/javascript">
var user = '{{request.user}}'
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;
}
var csrftoken = getCookie('csrftoken');
console.log(csrftoken)
</script>
</head>
然后在 body 下,我有以下脚本标记,我在其中检索 csrftoken 变量并将其传递给 'X-CSRFToken' header 在 fetch():
<body>
<script type="text/javascript">
console.log('Hello World')
console.log(csrftoken)
var updateButtons = document.getElementsByClassName('update-cart')
for(i = 0; i < updateButtons.length; i++){
updateButtons[i].addEventListener('click', function(){
var productId = this.dataset.product
var action = this.dataset.action
console.log('productId: ', productId, 'action: ', action)
console.log('user: ', user)
if(user === 'AnonymousUser'){
console.log('Not logged in.')
}else{
updateUserOrder(productId, action)
}
})
}
function updateUserOrder(productId, action){
console.log('User is authenticated. Sending data...')
console.log(csrftoken)
var url = '/update_item/'
fetch(url, {
method: 'POST',
headers: {
'Content-Type':'application/json',
'X-CSRFToken':csrftoken,
},
body: JSON.stringify({'productId': productId, 'action': action})
})
.then((response) => {
return response.json()
})
.then((data) => {
console.log('data: ', data)
})
}
</script>
</body>
所有 console.log() 调用都会显示 csrftoken 变量,但我仍然遇到以下异常:
(index):169 POST http://127.0.0.1:8000/update_item/ 500 (Internal Server Error)
updateUserOrder
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
views.py,
def update_item(request):
data = json.loads(request.data)
product_id = data['productId']
action = data['action']
print('action: ', action)
print('product_id: ', product_id)
customer = request.user.customer
product = Product.objects.get(id=product_id)
order, created = Order.objects.get_or_create(customer=customer, complete=False)
orderitem, created = OrderItem.objects.get_or_create(order=order, product=product)
if action == 'add':
orderitem.quantity += 1
elif action == 'remove':
orderitem.quantity -= 1
orderitem.save()
if orderitem.quantity <= 0:
orderitem.delete()
return JsonResponse('Item was added.', safe=False)
我似乎无法弄清楚这是语法错误还是我设置的 'X-CSRFToken' header 错误。其他类似的答案没有帮助。
已解决。这不是我的 javascript 或其中的 csrftoken 变量的问题。相反,它在我的服务器代码中。
在 views.py 中,我输入了 data = json.loads(request.data)
。不过应该是data = json.loads(request.body)
.