AWS Node JS with Request

前端 未结 1 1540
醉酒成梦
醉酒成梦 2021-01-28 01:36

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 =          


        
相关标签:
1条回答
  • 2021-01-28 02:22

    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

    0 讨论(0)
提交回复
热议问题