[英]HTTP Request in AWS Lambda is not working / NodeJS
i know, this topic was discussed very often.我知道,这个话题经常被讨论。 But these posts are either very old, or do not fix my problem.
但是这些帖子要么很旧,要么没有解决我的问题。 So i try it with opening a new (other) one.
所以我尝试打开一个新的(其他)一个。 I recently started making Alexa Skills.
我最近开始制作 Alexa Skills。 So now i managed to set up my AWS Lambda function with the help of (an also old) Tutorial.
所以现在我在(同样古老的)教程的帮助下设法设置了我的 AWS Lambda 函数。 Everything worked fine in the first step.
第一步一切正常。 So now i want to sent a GET Request to a website, just to get the status code.
所以现在我想向网站发送 GET 请求,只是为了获取状态代码。 In the next step, Alexa should tell me this code- but thats a diffrent story.
在下一步中,Alexa 应该告诉我这个代码——但那是一个不同的故事。 So i tried to get the request done with many different code snippets- but nothing worked.
所以我试图用许多不同的代码片段来完成请求 - 但没有任何效果。 After reading various posts, i understand that the code runs faster then the request can be executed.
阅读各种帖子后,我明白代码运行得更快,然后可以执行请求。 So the answer of the request does never show up in the logs.
所以请求的答案永远不会出现在日志中。 Which means, i cannot make use of it.
这意味着,我无法使用它。
This is my current code:这是我当前的代码:
exports.handler = async (event, context, callback) => {
try {
console.log(event)
if (event.session.new) {
console.log("new session");
}
switch (event.request.type) {
case "LaunchRequest":
console.log("LAUNCH REQUEST");
context.succeed(
generateResponse(
buildSpeechletResponse("This is a launch request", true), {}
)
)
break;
case "IntentRequest":
console.log("INTENT REQUEST")
switch (event.request.intent.name) {
case "checkConnection":
console.log("INTENT CHECK CONNECTION")
const https = require('https')
let url = "xxx/xxx/bc/alexa"
exports.handler = async function(event) {
console.log("async function")
const promise = new Promise(function(resolve, reject) {
https.get(url, (res) => {
resolve(res.statusCode)
}).on('error', (e) => {
reject(Error(e))
})
})
return promise
}
context.succeed(null, generateResponse(
buildSpeechletResponse("server answered with code " + this.statusCode, true), {}));
break;
}
case ("SessionEndedRequest"):
console.log("SESSION ENEDED REQUEST")
break;
default:
context.fail(`INVALID REQUEST TYPE: ${event.request.type}`);
break;
}
}
catch (error) { context.fail(`Exception: ${error}`) }
}
// Helpers
buildSpeechletResponse = (outputText, shouldEndSession) => {
console.log("buildSpeechletResponse");
return {
outputSpeech: {
type: "PlainText",
text: outputText
},
shouldEndSession: shouldEndSession
}
};
generateResponse = (speechletResponse, sessionAttributes) => {
console.log("generateResponse")
return {
version: "1.0",
sessionAttributes: sessionAttributes,
response: speechletResponse
}
};
If i test the code via the lambda test (including the JSON from Alexa to check connection), the log look like this.如果我通过 lambda 测试(包括来自 Alexa 的 JSON 来检查连接)测试代码,日志看起来像这样。
So as far as i see, th code runs to "INTENT CHECK CONNECTION", but the log "async function" never shows up.所以据我所知,代码运行到“意图检查连接”,但日志“异步功能”从未出现。 So what happens here?
那么这里会发生什么呢? Is the code skipped?
是否跳过了代码? How do i manage to get a working http request state of the art?
我如何设法获得最先进的 http 请求状态? (Sorry, if my post is not the "common way". It is also my first post)
(对不起,如果我的帖子不是“普通方式”。这也是我的第一篇帖子)
In your code exports.handler = async function(event) {} is the cause
exports.handler is always in entry function in AWS lambda export.handler 总是在 AWS lambda 的入口函数中
I just remove this code我只是删除此代码
exports.handler = async (event, context, callback) => {
try {
console.log(event)
if (event.session.new) {
console.log("new session");
}
switch (event.request.type) {
case "LaunchRequest":
console.log("LAUNCH REQUEST");
context.succeed(
generateResponse(
buildSpeechletResponse("This is a launch request", true), {}
)
)
break;
case "IntentRequest":
console.log("INTENT REQUEST")
switch (event.request.intent.name) {
case "checkConnection":
console.log("INTENT CHECK CONNECTION")
const https = require('https')
let url = "xxx/xxx/bc/alexa"
https.get(url, (res) => {
context.succeed(null, generateResponse(
buildSpeechletResponse("server answered with code " + res.statusCode, true), {}));
}).on('error', (e) => {
// handle error here
reject(Error(e))
})
})
break;
}
case ("SessionEndedRequest"):
console.log("SESSION ENEDED REQUEST")
break;
default:
context.fail(`INVALID REQUEST TYPE: ${event.request.type}`);
break;
}
}
catch (error) { context.fail(`Exception: ${error}`) }
}
// Helpers
buildSpeechletResponse = (outputText, shouldEndSession) => {
console.log("buildSpeechletResponse");
return {
outputSpeech: {
type: "PlainText",
text: outputText
},
shouldEndSession: shouldEndSession
}
};
generateResponse = (speechletResponse, sessionAttributes) => {
console.log("generateResponse")
return {
version: "1.0",
sessionAttributes: sessionAttributes,
response: speechletResponse
}
};
So i figured it out.所以我想通了。 The code i provided was nearly correct.
我提供的代码几乎是正确的。 The request function needed to be capsuled into another function.
请求函数需要封装到另一个函数中。 With minor adjustments, it worked with this code:
经过微小的调整,它可以使用以下代码:
// HTTP Request Function
function httpGet(options) {
const https = require('https');
return new Promise(((resolve, reject) => {
const request = https.request(options, (response) => {
response.setEncoding('utf8');
let returnData = '';
if (response.statusCode < 200 || response.statusCode >= 300) {
return reject(new Error(`${response.statusCode}: ${response.req.getHeader('host')} ${response.req.path}`));
}
response.on('data', (chunk) => {
returnData += chunk;
});
response.on('end', () => {
resolve(response.statusCode); //Fill response with status code
});
response.on('error', (error) => {
reject(error);
});
});
request.end();
}));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.