Reputation: 181
I have a web application making an ajax request to a server in node.js, however at the request, I always receive an error in the server console:
SyntaxError: Unexpected token # in JSON at position 0
However in Postman, I send the same request and it goes through just fine. I'm so sure that there's something wrong in my ajax request, but I've been working on this for days and I can't figure out what.
Here's the ajax request:
$.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);
}
});
Here's the server handler:
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");
});
Upvotes: 1
Views: 3675
Reputation: 181
Following the advice from the comments, the problem was solved by using JSON.stringify to convert the request data into valid JSON formatting. Here is the working code:
$.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);
}
});
Credit to @gargkshitiz and @DannyDainton for the above solution.
Upvotes: 1