问题
I am trying to write a lambda function which will make 3 http calls to the endpoints of my service running in the ec2 instance of my pod , the aws lambda will be triggered by the cron which I have configured, I have also added the VPC in the network setting while configuring the aws lambda.
I am using node.js 8.10 to code my lambda handler function , here is my code for the lambda handler function
'use strict';
var http = require('http');
exports.handler = async (event) => {
http.get('url1', function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
http.get('url2', function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
http.get('url3', function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
console.log('end request to');
}
I also tried this
'use strict';
var http = require('http');
exports.handler = async (event,context) => {
http.get('url1', function(res) {
console.log("Got response: " + res.statusCode);
context.succeed();
}).on('error', function(e) {
console.log("Got error: " + e.message);
context.done(null, 'FAILURE');
});
http.get('url2', function(res) {
console.log("Got response: " + res.statusCode);
context.succeed();
}).on('error', function(e) {
console.log("Got error: " + e.message);
context.done(null, 'FAILURE');
});
http.get('url3', function(res) {
console.log("Got response: " + res.statusCode);
context.succeed();
}).on('error', function(e) {
console.log("Got error: " + e.message);
context.done(null, 'FAILURE');
});
console.log('end request to');
}
but in both the cases I get this:
START RequestId: 0fa5225f-a54f-11e8-85a9-83174efb4714 Version: $LATEST
2018-08-21T14:32:41.855Z 0fa5225f-a54f-11e8-85a9-83174efb4714 end request to
END RequestId: 0fa5225f-a54f-11e8-85a9-83174efb4714
REPORT RequestId: 0fa5225f-a54f-11e8-85a9-83174efb4714
I referred to this answer
Is there any reason why it is not working ?
回答1:
Taking advantage of the (more recent) async/await functionality, and also cutting down on boilerplate, you could make your requests like so:
const get = async (requestUrl) => {
return new Promise((resolve, reject) => {
http.get(requestUrl, function(res) {
console.log("Got response: " + res.statusCode);
resolve(res);
}).on('error', function(e) {
console.log("Got error: " + e.message);
reject(e);
});
});
}
Define that function in your lambda file and then you can call it within the handler function like so:
const response1 = await get('url1');
Then your lambda should run properly.
For more info on using async
functions with AWS Lambda see this blog post from when they introduced the Node.js 8.10 runtime to AWS Lambda (thus allowing async/await
functionality).
来源:https://stackoverflow.com/questions/51951099/node-able-to-make-http-request-node-js-aws-lambda