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

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

这只是加入购物车的功能。也意味着将字段插入数据库。 添加到数据库时一切正常,但是每次我单击添加到购物车时都会出现此错误(但仍然添加到数据库)。

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

这是我的获取代码,导致调用我的控制器。我不确定这里返回的 json 数据是什么,正如您所看到的,我正在尝试 console.log(结果),以便我可以在失败与否时采取适当的措施。但我没有得到任何输出,可能是因为我得到的错误。

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


    })

}

这里是将产品 ID 插入数据库的控制器:

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

        })
    })
}

我对 promises 和 async 不是很熟悉,在 javascript 中等待。实际上,您可以看到我在此处的控制器代码中放置了 async 和 await,因为在此之前,我根本无法插入数据库。我添加了那些 async 和 await,但仍然不太了解它们是如何 work.Because 我以前没有在我的任何代码中使用它们,其结构与此处当前的问题代码几乎相同。可能是因为我现在在这里有两个回调函数,它们的工作方式和以前不一样了? (没有异步和等待)。

只是指出,我只想先从我的 console.log(结果)输出。

我发现您的代码有一些改进可能会解决问题:

首先,你应该在你的 fetch 调用上使用 catch 并且你应该在解析之前打印你的结果 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));
}

有了它,您应该能够获得有关错误的更多信息。

那么,在你的后端方法中,你使用的async/await是错误的:

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

我不确定你想 return 在你的后端 addToCart 中做什么,但我认为你 return 你想要什么会很容易。