gpt4 book ai didi

Node.JS 从 Http 请求 POST 获取数据

转载 作者:太空宇宙 更新时间:2023-11-04 01:51:20 24 4
gpt4 key购买 nike

我是 Node.js 新手,正在用 Node.js 编写 AWS Lambda 函数,以从 REST 端点获取数据并将数据发送回 Alexa。下面是我的代码片段:

  var req = http.request(post_options, function(response) {
var str = '';

response.setEncoding('utf8');

//another chunk of data has been recieved, so append it to `str`
response.on('data', function(chunk) {
str += chunk;
});

//the whole response has been recieved, so we just print it out here
response.on('end', function() {

var result = JSON.parse(str);

text = 'According to Weather Underground, the temperature in ' + citySlot + ',' + stateSlot + ' feels like ';
text += result.HighFahr0 + " degrees fahrenheit.";

console.log("text::"+text);
});
});

req.write(post_data);
//this.emit(':ask', text, "Anything else i can help you with?");
req.end();

如果我在构建文本字符串后立即执行 this.emit,它将不起作用。如果我在 req.write 函数之后执行 this.emit ,则文本变量超出范围并且不包含任何内容。如何在 req.write() 和 req.end() 之后获取文本变量的内容?

非常感谢。

最佳答案

在请求之前声明文本。我希望它能够发挥作用。

var text;
var req = http.request(post_options, function(response) {
var str = '';

response.setEncoding('utf8');

//another chunk of data has been recieved, so append it to `str`
response.on('data', function(chunk) {
str += chunk;
});

//the whole response has been recieved, so we just print it out here
response.on('end', function() {

var result = JSON.parse(str);

text = 'According to Weather Underground, the temperature in ' + citySlot + ',' + stateSlot + ' feels like ';
text += result.HighFahr0 + " degrees fahrenheit.";

console.log("text::"+text);
});
});

req.write(post_data);
this.emit(':ask', text, "Anything else i can help you with?");
req.end();

关于Node.JS 从 Http 请求 POST 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49559216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com