使用主体参数从 QnA 制造商 API 获得响应时出错

Error getting response from QnA maker API with body parameters

我编写了以下代码来调用 Microsoft QnA maker 生成答案 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);
});

但是,process.stdout.write(data); 部分正在打印错误代码 :Unspecified 以及一条消息 "please try after some time"。 我认为这里发生的是它在正文参数 written.So 之前返回响应 我的问题是,如何获得控制台中打印的 API 的响应。任何帮助将不胜感激。

https 包很灵活,但不是特别 user-friendly。您可以试试 request 吗?

无论如何,要使 POST 正常工作,您需要添加 Content-Length header。有关类似问题,请参阅 this

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