我有一个 Web 应用程序向 Node.js 中的服务器发出 ajax 请求,但是在请求时,我总是在服务器控制台中收到错误:
SyntaxError: Unexpected token # in JSON at position 0
但是在 Postman 中,我发送了相同的请求,并且进展顺利。我确信我的 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。
关于jquery - ajax 请求在 Postman 中工作,而不是在代码中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48299582/