AWS Lambda - NodeJS POST request and asynch write/read file

前端 未结 1 1805
梦毁少年i
梦毁少年i 2021-01-14 08:34

I am new to NodeJS and inside of AWS Lambda I am trying to make a POST request that calls an external API with a JSON object, creates a document with the response and then r

相关标签:
1条回答
  • 2021-01-14 09:10

    In general, I'd recommend starting like this:

    var querystring = require('querystring');
    var https = require('https');
    var fs = require('fs');
    
    exports.handler = function(event, context) {
        console.info('Received event', event);
    
        var data = {
            "accessKey": accessKey,
            "templateName": templateName,
            "outputName": outputName,
            "data": event.data
        };
    
        // Build the post string from an object
        var post_data = JSON.stringify(data);
    
        // An object of options to indicate where to post to
        var post_options = {
            host: 'hostname.com',
            port: '443',
            path: '/path/to/api',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': post_data.length
            }
        };
    
        var post_request = https.request(post_options, function(res) {
            var body = '';
    
            res.on('data', function(chunk)  {
                body += chunk;
            });
    
            res.on('end', function() {
                context.done(body);
            });
    
            res.on('error', function(e) {
                context.fail('error:' + e.message);
            });
        });
    
        // post the data
        post_request.write(post_data);
        post_request.end();
    };
    

    You can see I simplified your code quite a bit. I'd recommend avoiding the file system since that would slow down your program. I'm also not sure about what is the real goal of your function so I just return the HTTP response.

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