2017-07-06 21 views
0

我寫下面的代碼調用微軟QnA製造商生成答案API。從QnA製造商的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){ 
 
\t console.error(e); 
 
});

然而,process.stdout.write(data);部分打印錯誤代碼:未指定的,與消息一起 「請稍後再試」。 我認爲在這裏發生的事情是它正在寫體參數之前返回響應。所以我的問題是,我如何獲得在我的控制檯中打印的API的響應。任何幫助將不勝感激。

回答

0

https包是靈活的,但不是特別用戶友好。你可以試試request嗎?

無論如何,爲了讓您的POST工作,您需要添加Content-Length標題。有關類似問題,請參閱this

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