在Node.js中发出POST请求时的范围问题

时间:2017-07-11 17:36:01

标签: node.js post botframework

我正在尝试发出POST请求以从Microsoft Bot Framework访问QnA知识库。当我使用Hurl.it来测试我的API时,我得到了我想要的结果,在这种情况下,对我的问题“hi”的响应“你好”。当我运行代码时,我的变量/回调似乎超出了某个范围。错误返回null,而response.on('data'...或.end(......永远不会被调用。我已经尝试了http.request也没有成功。

var request = require('request');

var responseStr = "";

 request({
        url: "https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/<kb>/generateAnswer",
        method: "POST",
        json: true,
        headers: {
            "Content-Type" : "application/json",
            "Ocp-Apim-Subscription-Key":"<sub-key>",
        },
        body: {"question" : "hi"}
    }, function (error, response, body){
        session.send("Error: " + error);
        response.on("data", function(chunk){
            responseStr += chunk;
        });
        response.on("end", function(){
           session.send("EndWith: " + responseStr); 
        });

    });

1 个答案:

答案 0 :(得分:0)

试试这个:

var postData = {question : "hi"};

var options = {
    host: "westus.api.cognitive.microsoft.com/",
    port: 443,
    path: "/qnamaker/v2.0/knowledgebases/your_key/generateAnswer",
    method : 'POST',
    headers: {
        'Content-Type': 'application/json',
        "Ocp-Apim-Subscription-Key":"your_key",
    },
};

console.log(options);

var req = https.request(options, function(res) {
    res.on('data', function (chunk) {
        callback(null, chunk);
    });
});

req.on('error', function(e) {
    console.log('problem with request: ' + e.message);
});

req.write(JSON.stringify(postData));
req.end();
相关问题