我想知道是否有人可以提供帮助,因为我正为此苦苦挣扎。几天来我一直在寻找答案并尝试了各种方法,下面是我得到的最接近的答案。
基本上,我正在构建一个 Alexa 技能,供我在家中个人使用,为我儿子提供奖励积分,它会在我们的厨房仪表板上更新。我可以很好地发布积分并更新仪表板(更新 firebase 数据库)但是当我问 alexa 他有多少积分时我无法获得积分。我的代码如下。
const GetPointsHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest'
&& request.intent.name === 'HowManyPointsDoesNameHaveIntent';
},
handle(handlerInput) {
var options = {
"method": "GET",
"hostname": "blah-blah-blah.firebaseio.com",
"port": null,
"path": "/users/Connor/points.json",
"headers": {
"cache-control": "no-cache"
}
};
var req = https.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
//console.log(body.toString());
total = body.toString();
});
});
req.end();
speechOutput = "Connor has " + total + " points";
return handlerInput.responseBuilder
.speak(speechOutput)
.getResponse();
},
};
当我询问 alexa 时,结果是“Connor 有未定义的点”,但如果我立即再次询问,它会正常工作。
json 端点实际上只是在我将其加载到浏览器中时显示值,因此无需深入研究我认为不存在的响应。
我知道请求模块应该更简单,但是如果我使用 VS 代码命令行安装它并上传函数,因为文件变得如此之大,包含所有模块依赖项,我无法再在线编辑函数因为它超过了大小限制,所以尽可能避免这种情况。
我知道该函数更适合用作助手,一旦我开始工作,我就会这样做。我不需要它特别漂亮,只需要它能工作。
最佳答案
默认情况下,Node.js 是异步的,这意味着您的响应构建器在 GET 请求完成之前被调用。
解决方案:使用async-await,像这样
async handle(handlerInput) {
var options = {
"method": "GET",
"hostname": "blah-blah-blah.firebaseio.com",
"port": null,
"path": "/users/Connor/points.json",
"headers": {
"cache-control": "no-cache"
}
};
var req = await https.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
//console.log(body.toString());
total = body.toString();
});
});
req.end();
speechOutput = "Connor has " + total + " points";
return handlerInput.responseBuilder
.speak(speechOutput)
.getResponse();
},
如果这不起作用,请告诉我。还可以开发供个人使用的 alexa 技能,结帐 alexa blueprints .
关于javascript - Amazon Alexa Skill Lambda Node JS - Http GET 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52791202/