jQuery发布到node.js – >没有request.body目前

我想问你的帮助。 我有点卡住了,没有示例代码或谷歌的结果可以帮助。 我不知道什么是错的。

我做了一个jQuery发布请求到我的node.js服务器,如下所示:

$.ajax({ type : 'POST', url : "http://localhost:3000/connect-to-random-user", cache : false, dataType : 'json', contentType : 'application/json', data : { who : myUserId }, sucess : function(resp) { console.log("AAAAAAAAAA"); console.log(resp); console.log(JSON.stringify(resp)); console.log("requestNewPartner resp: "+JSON.stringify(resp.id)); if ( resp.id == "" ) { console.log("No free users available"); setTimeout(requestNewPartner, 200); } var call = videoPeer.call(resp.id, stream); call.on('stream', function (remoteStream) { $("#remoteVideo").prop('src', URL.createObjectURL(stream)); $("#conversationBox").append("Video Channel estabilished."); }); chatConn = chatPeer.connect(resp.id); chatConn.on('open', function() { $("#conversationBox").append("Connected to a stranger"); $("#messageBox").val(""); }); }, error : function (resp) { console.log("ERROR requestNewPartner: "+JSON.stringify(resp)); } }); 

节点中的代码:

 app.post('/connect-to-random-user', function (req, res) { /* if (req.hasOwnProperty('body')) { if (req.body.hasOwnProperty('data')) console.log("request has data field"); if (req.body.hasOwnProperty('who')) console.log("request has who field"); } else console.log("request has no body"); console.log("asd"); appdata.users[req.body.who] = ""; console.log("Connecting "+req.who+" to random user.."); for (var id in users) if ( appdata.users[req.who] !== appdata.users[id] && appdata.users[id] == "" ) { appdata.users[req.who] = id; appdata.users[id] = req.who; break; } console.log("Connected to "+appdata.users[req.who]);*/ console.log("random-user request received"); /*res.contentType('json'); res.send({ id: appdata.users[req.who]});*/ //console.log(" content: "+req); //console.log("stringified content: "+JSON.stringify(req)); console.log("stringified content2: "+JSON.stringify(req.params)); console.log("stringified content3: "+JSON.stringify(req.body)); res.send("WHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOOOOOOOOOOOOAAAAAAA"); 

});

我得到了一个错误的响应,以下控制台打印:

 random-user request received stringified content2: {} stringified content3: undefined 

也尝试发布string化的对象作为数据没有运气。

可能是什么问题? 任何帮助将非常感激。 我知道这是一个重复的问题,但现有的解决scheme并没有帮助我。 在此先感谢,伙计们!

尝试使用body-parser模块。

 var bodyParser = require('body-parser') var app = express() // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json()) 

您的应用程序需要身体分析中间件。

由于您的数据types是JSON,因此您应该可以使用Body Parser包(可用于npm install body-parser

将来,如果您处理多部分表单数据(例如从标准的Web表单), multer也可能是有用的。