I am trying to make a POST request to a knowledgebase. I can get the correct response from the request maybe 5-10% of the time. All the other times I get the error in the title back from the server:
No argument passed{“Error”:{“Code”:“BadArgument”,“Message”:“Request body Is Null or Empty.”}}
I have a feeling this is caused by Node.js being async and my variable is still undefined when the request goes through. Although, how can it when req.write()
includes the variable? Maybe I can insert a delay to insure the variable is defined before the request is sent?
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'
});