Uncaught (in promise) SyntaxError: Unexpected end of JSON input error

This is simply add to cart function. Also means insert field to database. All is fine when it comes to adding to the database, however there is this error everytime I click add to cart(But still adds to database though).

Uncaught (in promise) SyntaxError: Unexpected end of JSON input

Here is my fetch code, leading to calling my controller. I’m not sure what json data is being returned here, as you can see I’m trying to console.log(result), so that I can take proper actions if failed or not. But I’m not getting any output, maybe because of the error I’m getting.

    function addToCart(productId){

    fetch(`${rootUrl}api/users/addToCart/${productId}`,{

        method: "PUT",
        headers:{

            "Content-Type": "application/json",
            "Authorization": `Bearer ${token}`
        }

    })
    .then(result =>result.json())
    .then(result =>{

        console.log(result);


    })

}

And here is the controller that inserts product ID to the database:

module.exports.addToCart = async (userId, isAdmin, productId) =>{

if (isAdmin === true) {

    console.log('Not an admin function');

}else{

    const addToCartStatus = await User.findById(userId).then((user, error)=>{

        user.cartItems.push({item: productId});

        return user.save().then((result, error)=>{

            if(error){

                
                return false;

            }else{

                return true;
            }

        })
    })
}

I’m not that familiar with promises and async, await in javascript. Actually, you can see I put async and await in my controller code here because, before that, I can’t even insert to the database at all. I added those async and await, but still don’t understand much how they work.Because I don’t use them before in any of my codes with almost the same structure as the current problem code here. Maybe because I have now two callback functions here and that doesn’t work the same as before? (without the async and await).

Just to point out, I just want output first from my console.log(result).

Answer

I see some improvements in your code that might resolve the problem:

First of all, you should use catch on your fetch call and you should print your result before to parse as json:

function addToCart(productId){
    fetch(`${rootUrl}api/users/addToCart/${productId}`,{
        method: "PUT",
        headers:{
            "Content-Type": "application/json",
            "Authorization": `Bearer ${token}`
        }
    })
   .then(result => {
       console.log(result);
       return result.json();
   })
   .then(result =>{
       console.log(result);
    })
   .catch(e => console.log(e));
}

With that you should be able to get more info about the error.

Then, in your backend method, you are using async/await wrong:

module.exports.addToCart = async (userId, isAdmin, productId) => {
    if (isAdmin !== true) {
        console.log('Not an admin function');
        return;
    }

    try {
        const user = await User.findById(userId);
        user.cartItems.push({ item: productId });
        const saveResult = await user.save();

        return saveResult;
    } catch (e) {
        console.log(e);
    }
};

I’m not shure what do you want to return in your backend addToCart but I think it will be easy for you to return what you want.