我正在尝试向知识库发出POST请求。可能只有5-10%的时间我能够从请求中得到正确的响应。其他时候,我会从服务器上收到标题中的错误信息。请保留HTML标记。
No argument passed{“Error”:{“Code”:“BadArgument”,“Message”:“Request body Is Null or Empty.”}}
我有一种感觉,这是由于Node.js是异步的,并且在请求发送时我的变量仍然未定义所致。虽然实际上req.write()
中包含了该变量,但它可能还没有被定义。也许我可以插入一个延迟来确保在发送请求之前变量已经被定义?
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'
});
postData
来检查一下。 你的代码看起来很简单明了,找不到哪里可能出错了。 - Sigmabot.dialog('qnaReq',function (session, args) {
这一行之后声明你的options
对象。 也许内容长度破坏了你的函数。 当你连续两次使用相同的主体调用API时,它似乎是有效的。 - Sigma