node.js – POST请求正文为空或空

我正在尝试向知识库发出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提到的问题.

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

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...