【问题标题】:POST Request body Is Null or EmptyPOST 请求正文为 Null 或为空
【发布时间】:2017-07-24 20:56:17
【问题描述】:

我正在尝试向知识库发出 POST 请求。我可以从请求中得到正确的响应,可能有 5-10% 的时间。所有其他时间我都从服务器收到标题中的错误:

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'
});

【问题讨论】:

  • 您确定您的会话不为空吗?你能 console.log 你的postData检查它。您的代码看起来很简单,找不到可能出错的地方。
  • 是的,console.log(postData) 完美运行。我不完全确定为什么我可以很好地查询我的结果然后再试一次,但在接下来的 15 次我尝试它时它不起作用
  • API 是否可能限制请求率?您可以通过邮递员或其他客户重现这种行为吗?
  • 您是否尝试过使用 postData 中的 top 字段。这似乎是可选的,但谁知道... { "question": "is qna maker free?", "top": 3 } westus.dev.cognitive.microsoft.com/docs/services/…
  • 使用 hurl.it 总是给我一个正确的回应。我以前没有使用过邮递员,但我可以研究一下。

标签: node.js post botframework


【解决方案1】:

这似乎是here提到的问题。

尝试使用Content-Length Header 中提到的here

【讨论】:

    【解决方案2】:

    您的代码看起来正确。您使用http.request() 发出请求并执行req.write()req.end()(请注意,您可以跳过写入部分,直接执行req.end(data))。

    我认为这里的关键是当您执行 req.write() 时数据会发生什么:

    var postData = {问题:session.message.text};

    您确定session.message.text 不是undefined?因为如果是,那么postData 将是{ question: undefined },字符串化后变为'{}'

    【讨论】:

      猜你喜欢
      • 2021-03-20
      • 2018-11-28
      • 2018-06-16
      • 2019-06-26
      • 2018-08-03
      • 2015-09-08
      • 2016-06-01
      • 1970-01-01
      • 2022-01-06
      相关资源
      最近更新 更多