OwenC
OwenC

Reputation: 13

Fetch returning 500(internal server error) JavaScript

I have had a hunt around but can't seem to find an answer that works. I am following Dennis Ivy's Django tutorial for an e-commerce website but I have run in to an issue where I am trying to add an item to my cart but nothing happens, checking the console I am getting these two errors:

POST http://127.0.0.1:8000/update_item/ 500 (Internal Server Error)

updateUserOrder @ cart.js:26 (The fetch line)

(anonymous) @ cart.js:15 (when the function is called)

127.0.0.1/:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

omise.then (async)

updateUserOrder @ cart.js:39 (the second .then)

(anonymous) @ cart.js:15 (when the function is called)

Here is my JavaScript cart.js updateUserOrder function:

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()
            });
    }

Here is my view 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)

Here is my URL including import:

from checkout.views import updateItem

path('update_item/', updateItem, name="update_item"),

Thanks in advance!

Upvotes: 0

Views: 13221

Answers (2)

Nnamani William
Nnamani William

Reputation: 31

In ur JavaScript file in location.reload() You shouldn't add a semi-colon after that curly brace and parentheses })

Upvotes: 0

cuspymd
cuspymd

Reputation: 1088

About first error POST http://127.0.0.1:8000/update_item/ 500 (Internal Server Error), you need to check server logs.

About second error 127.0.0.1/:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0, the Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 500. Instead, it will resolve normally (with ok status set to false). So you need to add codes checking the response in then() like below.

...
            .then((response) => {
                if (!response.ok) {
                    // error processing
                    throw 'Error';
                }
                return response.json()
            })
...

Upvotes: 7

Related Questions