Uncaught (in promise) SyntaxError: Unexpected end of JSON input error
Posted
技术标签:
【中文标题】Uncaught (in promise) SyntaxError: Unexpected end of JSON input error【英文标题】: 【发布时间】:2021-11-06 00:54:17 【问题描述】:这只是添加到购物车功能。也意味着将字段插入数据库。 添加到数据库时一切都很好,但是每次单击添加到购物车时都会出现此错误(但仍会添加到数据库中)。
Uncaught (in promise) SyntaxError: Unexpected end of JSON input
这是我的获取代码,导致调用我的控制器。我不确定这里返回的是什么 json 数据,如您所见,我正在尝试 console.log(result),以便在失败与否时可以采取适当的措施。但我没有得到任何输出,可能是因为我遇到了错误。
function addToCart(productId)
fetch(`$rootUrlapi/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;
)
)
我对 Promise 和 async 不太熟悉,在 javascript 中等待。实际上,您可以看到我在这里将 async 和 await 放入我的控制器代码中,因为在此之前,我什至根本无法插入数据库。我添加了这些异步和等待,但仍然不太了解它们是如何工作的。因为我之前没有在我的任何代码中使用它们,其结构与此处的当前问题代码几乎相同。也许是因为我现在在这里有两个回调函数,并且与以前的工作方式不同? (没有 async 和 await)。
只是指出,我只想先从我的 console.log(result) 输出。
【问题讨论】:
【参考方案1】:我发现您的代码中有一些改进可能会解决问题:
首先,你应该在你的 fetch 调用中使用 catch 并且你应该在解析为 json 之前打印你的结果:
function addToCart(productId)
fetch(`$rootUrlapi/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);
;
我不确定你想在后端 addToCart 中返回什么,但我认为返回你想要的内容对你来说很容易。
【讨论】:
谢谢。我仍在测试并试图理解您的代码,但目前它似乎比第一个更干净。以上是关于Uncaught (in promise) SyntaxError: Unexpected end of JSON input error的主要内容,如果未能解决你的问题,请参考以下文章
解决Uncaught (in promise) reason的问题
Uncaught (in Promise) DOMException: play() 只能由用户手势启动
解决Uncaught (in promise) reason的问题
Uncaught (in promise):消息端口在收到响应之前关闭
vue控制台报 Uncaught (in promise) TypeError:
Uncaught (in promise) TypeError: Cannot set properties of null (setting 'innerText') in OpenWetherMa