获取返回 500(内部服务器错误)JavaScript

0 javascript django fetch-api

我四处寻找,但似乎找不到有效的答案。我正在遵循 Dennis Ivy 的电子商务网站 Django 教程,但遇到了一个问题,我试图将商品添加到购物车但没有任何反应,检查控制台时出现以下两个错误:

POST http://127.0.0.1:8000/update_item/ 500(内部服务器错误)

updateUserOrder @ cart.js:26 (获取行)

(匿名)@ cart.js:15(调用函数时)

127.0.0.1/:1 未捕获(承诺中)语法错误:JSON 中位置 0 处出现意外标记 <

omise.then(异步)

updateUserOrder @ cart.js:39 (第二个 .then)

(匿名)@ cart.js:15(调用函数时)

这是我的 JavaScript cart.js updateUserOrder 函数:

function updateUserOrder(productId, action) {
        console.log('User is logged in, sending data...')

        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) => {
                location.reload()
            });
    }
Run Code Online (Sandbox Code Playgroud)

这是我的观点updateItem

def updateItem(request):
    data = json.loads(request.body)
    productId = data['productId']
    action = data['action']
    print('Action:', action)
    print('Product:', 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(order=order, product=product)

    if action == 'add':
        orderItem.quantity = (orderItem.quantity + 1)
    elif action == 'remove':
        orderItem.quantity = (orderItem.quantity - 1)

    orderItem.save()

    if orderItem.quantity <= 0:
        orderItem.delete()

    return JsonResponse('Item was added', safe=False)
Run Code Online (Sandbox Code Playgroud)

这是我的 URL,包括导入:

from checkout.views import updateItem

path('update_item/', updateItem, name="update_item"),
Run Code Online (Sandbox Code Playgroud)

提前致谢!

小智 5

关于第一个错误POST http://127.0.0.1:8000/update_item/ 500 (Internal Server Error),您需要检查服务器日志。

\n

关于第二个错误,从fetch()127.0.0.1/:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0返回的 Promise不会\xe2\x80\x99t 在 HTTP 错误状态下拒绝,即使响应是 HTTP 500。相反,它将正常解析(ok 状态设置为 false)。因此,您需要添加代码来检查响应,如下所示。then()

\n
...\n            .then((response) => {\n                if (!response.ok) {\n                    // error processing\n                    throw \'Error\';\n                }\n                return response.json()\n            })\n...\n
Run Code Online (Sandbox Code Playgroud)\n