Home > Software design >  MongoDB doesn't save correctly passed data with $ajax
MongoDB doesn't save correctly passed data with $ajax

Time:07-27

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. enter image description here

What's the problem?

Thanks ahead!

P.S. data -> Object generated by class

CodePudding user response:

You can try like this.

Server Side:

router.post('/v2', async (req, res) => {

if (!req.body) {
    res.status(400).json({ message: "Data not found" })
    return;
}

console.log(req.body)

const person = new Person({
    firstName: req.body.firstName,
    secondName: req.body.secondName
})

try {
    await person.save()
    res.status(201).json({ message: "Data stored successfully" })

} catch (error) {
    res.status(500).json({ message: "Internal server error" })
}

})

Ajax Request

function addUserToDB() { $.ajax({

    method: 'POST',

    url: 'URL/v2',

    headers: { "Accept": "application/json; odata=verbose" },

    data: { firstName, secondName },

    success: function (result, stat, xhr) {
        console.log(xhr.responseJSON)
    },

    error: function (xhr, status, error) {

        console.log(xhr.responseJSON)

    }

})

}

CodePudding user response:

I found the answer to my problem to be:

headers: {
    "Content-type": "application/json"
},

data: JSON.stringify(data)
  • Related