简体   繁体   中英

How can I properly send Objects via AJAX using bodyParser in node.js express?

I'm trying to do:

$.ajax({
    type:"POST",
    url:"/psychos",
    data:JSON.stringify(this.psycho)        
})

At server I got:

app.post("/psychos", function(request, response) {

    var psychologist = request.body.psycho
    console.log(psychologist)


    psicologosCollection.insert(psychologist, function(error, responseFromDB) {

        if (error) {response.send(responseFromDB)}

        console.log("Se ha insertado: "+ JSON.strinfigy(responseFromDB))
        response.send(responseFromDB)
    })
})

But, the console.log() is printing undefined and got the following throw:

TypeError: Cannot read property '_id' of undefined
    at insertWithWriteCommands (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/mongodb/lib/mongodb/collection/core.js:78:13)
    at Collection.insert (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/mongodb/lib/mongodb/collection/core.js:30:7)
    at Object.handle (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/server.js:117:25)
    at next_layer (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/route.js:103:13)
    at Route.dispatch (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/route.js:107:5)
    at c (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/index.js:195:24)
    at Function.proto.process_params (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/index.js:251:12)
    at next (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/index.js:189:19)
    at next (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express/lib/router/index.js:166:38)
    at Layer.session [as handle] (/home/diegoaguilar/DigitalOcean/psicologostuxtepec/node_modules/express-session/index.js:98:29)

I'm using BodyParser before:

var bodyParser  = require('body-parser')
app.use(bodyParser())

psycho is actually a valid existing object. At the method where AJAX is performed a console.log(this.psycho) will print my object. What am I doing wrong?

Edit:

Even I found out I should have got:

var psychologist = request.body.psycho

at server GET route code, I can't understand how bodyParser generates an Object?

For a quite similar AJAX call I tried before:

function getSendingJSON(url,reqObject,callBack)  {
    $.ajax({
        type: "get",
        data: reqObject,
        dataType: "json",
        url: url,
        success: function(response){
           callBack(response);
        }
    });
}

So response was a JSON, and callback function looked similar to:

function plotReglaFalsa(respuesta) {

    if (respuesta.fail) {...}
    else if (respuesta.negative) {...}
    ....
}

Even that was purely at client side, I'm confused how to deal with Objects/JSON serialization and how bodyParser acts for it.

You have not serialized the data in your request, it's still just a JavaScript object until you serialize it as JSON:

$.ajax({
    type:"POST",
    contentType: "application/json",
    url:"/psychos",
    data: JSON.stringify( this.pyscho )
})

So call JSON.stringify in order to serialize as JSON and then the body parser has something to parse.

app.post("/psychos", function(request, response) {
 //change request.body.psycho to request.body
 var psychologist = request.body
 console.log(psychologist)
 psicologosCollection.insert(psychologist, function(error, responseFromDB) {

 if (error) {response.send(responseFromDB)}

    console.log("Se ha insertado: "+ JSON.stringify(responseFromDB))
    response.send(responseFromDB)
})
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM