0

I wrote the below code for calling microsoft QnA maker generate answer API.

var http=require('https');

var demo=[];
console.log("Doing the Post Operations...");
// Define an demo object with properties and values. This object will be used for POST request.

var demo=JSON.stringify({"question":"hi"});


var extServerOptionsPost={
  host:'westus.api.cognitive.microsoft.com',
  path:'/qnamaker/v2.0/knowledgebases/<my kb id>/generateAnswer',
  port:443,
  method:'POST',
  headers:{
    'Ocp-Apim-Subscription-Key':'my key',
    'Content-Type':'application/json'
  }
};

var reqPost=http.request(extServerOptionsPost,function(res){
console.log("response statusCode: ",res.statusCode);
res.on('data',function(data){
console.log('Posting Result:\n');
process.stdout.write(data);
console.log('\n\n POST Operation Completed');
});
});


reqPost.write(demo);


reqPost.end();
reqPost.on('error',function(e){
 console.error(e);
});

However, the process.stdout.write(data);part is printing error code :Unspecified , along with a message "please try after some time". What I think is happening here that it is returning the response before the body parameter is being written.So my question is, how do I get the response of the API printed in my console. Any help will be appreciated.

JSnow
  • 929
  • 2
  • 11
  • 24

1 Answers1

0

The https package is flexible, but not particularly user-friendly. Might you try request instead?

Anyway, to get your POST to work, you need to add the Content-Length header. See this for a similar question.

headers:{
    'Ocp-Apim-Subscription-Key':'my key',
    'Content-Type':'application/json',
    'Content-Length':Buffer.byteLength(demo)
}
cthrash
  • 2,938
  • 2
  • 11
  • 10