gpt4 book ai didi

javascript - jQuery 发布到 node.js -> 不存在 request.body

转载 作者:太空宇宙 更新时间:2023-11-04 00:50:38 26 4
gpt4 key购买 nike

我想请求你的帮助。我对此有点困惑,没有示例代码或谷歌结果可以提供帮助。我不知道出了什么问题。

我向我的 node.js 服务器发出了一个 jQuery post 请求,如下所示:

$.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));
}
});

Node 中的代码:

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

还尝试将字符串化对象作为数据发布,但运气不佳。

可能是什么问题?任何帮助将非常感激。我知道这是一个重复的问题,但现有问题的解决方案对我没有帮助。提前谢谢大家!

最佳答案

尝试使用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())

关于javascript - jQuery 发布到 node.js -> 不存在 request.body,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32671076/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com