I have been struggling all day with an issue while trying to send json data via ajax to Express. Here is how my ajax code looks like:
$('#saveClause').click(function () {
var username = document.getElementById('postUserName').innerHTML;
var clauseTitle = document.getElementById('modalTitle').innerHTML;
var clauseDescription = document.getElementById('modalDescription').innerHTML;
var clauseText = document.getElementById('modalText').innerHTML;
$.ajax({
url: "/classes/updateAssignment",
type: "post",
dataType: "json",
data: {
username: username,
title: clauseTitle,
description: clauseDescription,
text: clauseText
},
cache: false,
contentType: "application/json",
complete: function () {
console.log("complete");
},
success: function () {
console.log("success");
},
error: function () {
console.log("Process Error");
}
});
});
This is what my Express Classes routes look like:
router.post('/updateAssignment', function (req, res) {
console.log(req.body.username)
console.log(req.body.title);
console.log(req.body.description);
console.log(req.body.text);
res.type('json');
res.send({
some: JSON.stringify({
response: 'json'
})
});
});
When I sent a postman post request to the URL with this JSON object:
{
"username":"testing",
"title":"123",
"description":"j456",
"text":"seven"
}
Express was able to log all the details in the console without any issues, so it seems like there might be a problem with my ajax request as it's giving me an unexpected token u error. Any suggestions on what might be causing this?