我有一个Web应用程序向node.js中的服务器发出ajax请求,但是在请求时,我总是在服务器控制台中收到错误消息:
SyntaxError:JSON中位置0处的意外令牌#
但是,在邮递员中,我发送了相同的请求,并且一切顺利。我确定我的ajax请求中有问题,但是我已经为此工作了好几天,但我不知道是什么原因。
这是ajax请求:
$.ajax({
contentType: 'application/json',
url: "/insert/image_data",
method:"post",
data: {
tags: tag,
cats: cat
},
dataType: "json",
success:function(res){
console.log(res);
},
error: function(err){
console.log(err);
}
});
这是服务器处理程序:
app.post("/insert/image_data", function(req, res){
let imageData = req.body;
console.log("/insert/image_data route reached");
console.log("--> imageData = ", prettyjson.render(imageData));
res.status(200).send("Req GOOD");
});
根据评论的建议,使用JSON.stringify将请求数据转换为有效的JSON格式解决了该问题。这是工作代码:
$.ajax({
contentType: 'application/json',
url: "/insert/image_data",
method:"post",
data: JSON.stringify({
tags: tag,
cats: cat
}),
dataType: "json",
success:function(res){
console.log(res);
},
error: function(err){
console.log(err);
}
});
感谢上述解决方案的@gargkshitiz和@DannyDainton。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句