POST request body is null or empty

I am trying to make a POST request for a knowledge base. I can get the right answer from the request, perhaps in 5-10% of cases. The rest of the time I get an error in the header from the server:

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

I feel this is caused by Node.js being async, and my variable is still undefined when the request passes. Although, how can this be when req.write() includes a variable? Maybe I can insert a delay to ensure that the variable is defined before sending the request?

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

console results

enter image description here

+5
source share
2 answers

It seems the problem mentioned here .

Try using the Content-Length Header as mentioned here

0
source

Your code looks correct. You send a request using http.request() and do req.write() and req.end() (note that you can skip part of the record and just do req.end(data) ).

I think the key here is what happens to the data when you do req.write() :

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

Are you sure session.message.text not undefined ? Because if this is so, then postData will be { question: undefined } , which stringified becomes '{}' .

0
source

Source: https://habr.com/ru/post/1269789/


All Articles