如何正确地发送对象通过AJAX使用bodyParser在node.js express?

我正在尝试做:

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

在服务器我得到:

 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) }) }) 

但是, console.log()正在打印undefined并得到以下抛出:

 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) 

我以前使用BodyParser

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

心理学实际上是一个有效的现存对象。 在执行AJAX的方法console.log(this.psycho)将打印我的对象。 我究竟做错了什么?

编辑:

即使我发现我应该得到:

 var psychologist = request.body.psycho 

在服务器GET路由代码,我无法理解bodyParser如何生成一个对象?

对于我之前尝试的非常类似的AJAX调用:

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

所以响应是一个JSON,callback函数看起来类似于:

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

即使这纯粹是在客户端,我很困惑如何处理Objects / JSON序列化和BodyParser如何处理它。

你没有序列化你的请求中的数据,它仍然只是一个JavaScript对象,直到你序列化为JSON:

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

所以调用JSON.stringify为了序列化为JSON,然后身体parsing器有一些parsing。

 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) }) })