Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

python - JSONDecodeError in json.loads(request.body)

I am getting JSONDecodeError in data=json.loads(request.body)

cart.js:

function updateUserOrder(productId, action) {
    console.log('User is authenticated')
    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)
            location.reload()
        });
}

In views.py:

def updateItem(request):

data = json.loads(request.body)
productId = data['productId']
action = data['action']
print("Action:", action)
print("Product id", productId)
customer = request.user.customer
product = Product.objects.get(id=productId)

order, created = Order.objects.get_or_create(customer=customer, complete=False)

orderItem, created = OrderItem.objects.get_or_create(product=product, order=order)
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)

I am getting this error. JSONDecodeError at /update_item/ Expecting value: line 1 column 1 (char 0) Request Method: GET Request URL: http://127.0.0.1:8000/update_item/ Django Version: 3.1.3 Exception Type: JSONDecodeError Exception Value:
Expecting value: line 1 column 1 (char 0)

Python version: Python 3.8.6 Django version: 3.1.3

I tried following other posts in stackoverflow and tried using cherrypy and various other ways for json.loads(request.body). Please resolve this error.

Edit: Perhaps this may help:

Request information USER AnonymousUser

GET No GET data

POST No POST data


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

+1 vote
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...