node.js - POST 请求正文为 Null 或空

标签 node.js post botframework

我正在尝试向知识库发出 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 results

enter image description here

最佳答案

好像是提到的问题here .

尝试使用提到的 Content-Length header here

关于node.js - POST 请求正文为 Null 或空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45080723/

相关文章:

javascript - WebSocket 连接失败。 WebSocket 握手期间出错 - socketjs

javascript - 如何为 Node.js 中发生的每个错误发送电子邮件?

java - JAX-RS response.getEntity 在发布后返回 null

c# - Bot framework v4.0 如何在对话中执行前面的瀑布步骤

c# - BOT DirectLine 与 MVC 应用程序集成

javascript - mongodb/mongoose findOneandUpdate 如何获取索引和删除对象

node.js - Node-sass 错误(尝试重新安装)

http - 如何使用 scrapy 爬取依赖于帖子的网站

javascript - 将变量从 JS 发布到 PHP 时遇到问题

c# - 在 Microsoft Bot 框架 V4 中完成子对话框时,如何继续父对话框?