Reputation: 105
I am not sure whats wrong here but my lambda below in node js doesnt work
'use strict';
exports.handler = function (event, context) {
try {
var req = require('request');
var headers = { 'User-Agent': 'Super Agent/0.0.1' };
var options = {
url: 'http://google.com',
method: 'GET',
headers: headers
};
req(options, function (error, response, body) {
console.log(body);
});
The above is loading the module properly but it doesn't get to the console.log(body) for some reason. Anyone have an idea?
Upvotes: 1
Views: 5883
Reputation: 448
I am assuming that the code you posted is the code you wrote for lambda. AWS Lambda has specific entry point/function called handler which is runs when lambda is invoked. So every lambda function must have this method to qualify as lambda.
exports.handler = (event, context, callback) => {
}
Also external dependencies of lambda is not automatically pulled. Hence, we need to zip the entire code with dependencies and upload it to lambda for it to work in case we have external dependency.
Example
lambda.js
var req = require('request');
var headers = { 'User-Agent': 'Super Agent/0.0.1' };
// Configure the request
var options = {
url: 'http://google.com',
method: 'GET',
headers: headers
};
exports.handler = (event, context, callback) => {
req(options, function (error, response, body) {
console.log(body);
callback(error);
});
}
Now let us consider your directory structure to be as
node_modules/
lambda.js
package.json
Now you need to zip this content and upload it to lambda in AWS. Next thing is to point the lambda.js as handler for the present lambda.
If everything is done correctly, you can see now the log in cloudwatch after the lambda is invoked.
References:
http://docs.aws.amazon.com/lambda/latest/dg/get-started-create-function.html http://docs.aws.amazon.com/lambda/latest/dg/nodejs-create-deployment-pkg.html
Upvotes: 2