I am struggling with understanding what causes my script(s) to not add data that I send with ajax request. Instead of data that I pass it adds " "
(obviously because it cannot parse the body for some reason)
What may cause this problem?
Server side:
router.post('/v2', async (req, res) => {
console.log(req.body)
const person = new Person({
firstName: req.body.firstName || ' ',
secondName: req.body.secondName || ' '
})
try {
const newPerson = await person.save()
res.status(201).json({ message: { id: newPerson._id } })
} catch (error) {
res.status(400).json({ message: error.message })
}
})
Ajax request:
function addUserToDB(data) {
const promisedResponse = v2Request(data);
promisedResponse.done(function (data) {
console.log(data.message.id)
});
function v2Request(data) {
return $.ajax({
type: "post",
headers: {
"Accept": "application/json; odata=verbose"
},
url: "URL/v2",
data: data,
processData: false,
dataType: "json"
});
}
}
Code works fine as it returns correct response, but still with " "
data added to db.
What’s the problem?
Thanks ahead!
P.S. data -> Object generated by class
2
Answers
I found the answer to my problem to be:
You can try like this:
Server Side:
Ajax Request