POST请求正文为空或空

我正在尝试向知识库发出POST请求。 我可以从这个请求中得到正确的答案,也许5-10%的时间。 所有其他时间,我从服务器得到标题中的错误:

No argument passed{“Error”:{“Code”:“BadArgument”,“Message”:“Request body Is Null or Empty.”}} 

我有一种感觉,这是由Node.jsasynchronous引起的,当请求通过时,我的variables仍然是未定义的。 虽然, req.write()如何包含variables? 也许我可以插入一个延迟来确保variables是在请求发送之前定义的?

 var https = require('https'); var resData = ""; var options = { host: "westus.api.cognitive.microsoft.com", port: 443, path: "/qnamaker/v2.0/knowledgebases/<kb-key>/generateAnswer", method : 'POST', headers: { 'Content-Type': 'application/json', "Ocp-Apim-Subscription-Key":"<sub-key>", }, }; bot.dialog('qnaReq', function (session, args) { //call QnA Bot and ask that bot the question var req = https.request(options, function(res) { res.on('data', function (chunk) { resData += chunk; }); res.on('error', function(e) { console.log('problem with request: ' + e.message); }); res.on('end', function() { if (resData.length != 75) { //75 is the length of the error I get almost every time. This line prevents the application from crashing since I am trying to access values that won't be there. var accessibleData = JSON.parse(resData); session.send(accessibleData["answers"][0]["answer"]); } else { session.send("No argument passed" + resData); } resData = ""; }); }); var postData = {question: session.message.text}; console.log(postData); //postData is defined req.write(JSON.stringify(postData)); req.end(); }).triggerAction({ matches: 'IT Help' }); 

控制台结果

在这里输入图像描述

这似乎是这里提到的问题。

尝试使用这里提到的Content-Length Header

你的代码看起来正确。 你使用http.request()发出一个请求,并执行一个req.write()和一个req.end() (注意你可以跳过写部分,只是做req.end(data) )。

我认为这里的关键是当您执行req.write()时数据会发生什么req.write()

var postData = {question:session.message.text};

你确定session.message.text不是undefined吗? 因为如果是这样的话,那么postData就是{ question: undefined } ,这个string变成了'{}'