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


source share