从Node.js调用Microsoft QnA制造商API

时间:2017-06-20 14:01:28

标签: node.js api microsoft-cognitive

这是我编写的代码示例



var http=require('http');

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:'http://westus.api.cognitive.microsoft.com/qnamaker/v2.0',
path:'/knowledgebases/<my kb id>/generateAnswer',
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);
});
&#13;
&#13;
&#13;

当我运行它时,它显示以下错误。 enter image description here

如何解决此错误?这是我第一次从节点调用第三方API。在这方面的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

主机名不应包含协议,顺便说一句,它必须是https,而不是http。所以:

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