AWS Lambda HTTP POST Request (Node.js)
Asked Answered
R

3

24

I'm relatively new to AWS lambda function and nodejs. I'm working on to try and get the list of 5 cities in a country by using HTTP POST request from this website: "http://www.webservicex.net/globalweather.asmx?op=GetCitiesByCountry"

I've been searching about how to do a HTTP POST request in lambda function but I can't seem to find a good explanation for it.

Searches that I found for http post:

https://www.npmjs.com/package/http-post How to make an HTTP POST request in node.js?

Reefer answered 21/11, 2017 at 2:39 Comment(4)
Possible duplicate of How to send http request with nodejs AWS Lambda?Veliavelick
You should send http.request with POST as method. See this on nodejs.org for further details nodejs.org/api/http.html#http_http_request_options_callbackOvariotomy
Thanks guys I'll be looking into these.Reefer
Useful blog post here: sabljakovich.medium.com/…Pallette
M
2

Try the following sample, invoking HTTP GET or POST request in nodejs from AWS lambda

const data = {
    "data": "your data"
};
const options = {
    hostname: 'hostname',
    port: port number,
    path: urlpath,
    method: 'method type'
};
    
const req = https.request(options, (res) => {
    res.setEncoding('utf8');
    res.on('data', (chunk) => {
    // code to execute
});
res.on('end', () => {
    // code to execute      
    });
});
req.on('error', (e) => {
     callback(null, "Error has occured");
});
req.write(data);
req.end();

Consider the sample

Messaline answered 21/11, 2017 at 8:58 Comment(1)
Where is the post body passed in this solution?Dagostino
I
39

I think that the cleaner and more performant way, without the need for external libs, can be something like this:

const https = require('https');

const doPostRequest = () => {
  const data = {
    value1: 1,
    value2: 2,
  };

  return new Promise((resolve, reject) => {
    const options = {
      host: 'www.example.com',
      path: '/post/example/action',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      }
    };
    
    // create the request object with the callback with the result
    const req = https.request(options, (res) => {
      resolve(JSON.stringify(res.statusCode));
    });

    // handle the possible errors
    req.on('error', (e) => {
      reject(e.message);
    });
    
    // do the request
    req.write(JSON.stringify(data));

    // finish the request
    req.end();
  });
};

exports.handler = async (event) => {
  await doPostRequest()
    .then(result => console.log(`Status code: ${result}`))
    .catch(err => console.error(`Error doing the request for the event: ${JSON.stringify(event)} => ${err}`));
};

This lambda has been made and tested on the following Runtimes: Node.js 8.10 and Node.js 10.x and is able to do HTTPS requests. To do HTTP requests, you need to import and change the object to http:

const http = require('http');
Implement answered 31/7, 2019 at 14:38 Comment(0)
L
17

I had difficulty implementing the other answers so I'm posting what worked for me.

In this case the function receives url, path and post data

Lambda function

var querystring = require('querystring');
var http = require('http');

exports.handler = function (event, context) {
var post_data = querystring.stringify(
      event.body
  );

  // An object of options to indicate where to post to
  var post_options = {
      host: event.url,
      port: '80',
      path: event.path,
      method: 'POST',
      headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': Buffer.byteLength(post_data)
      }
  };

  // Set up the request
  var post_req = http.request(post_options, function(res) {
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
          console.log('Response: ' + chunk);
          context.succeed();
      });
      res.on('error', function (e) {
        console.log("Got error: " + e.message);
        context.done(null, 'FAILURE');
      });

  });

  // post the data
  post_req.write(post_data);
  post_req.end();

}

Example of call parameters

   {
      "url": "example.com",      
       "path": "/apifunction",
       "body": { "data": "your data"}  <-- here your object
    }
Lanai answered 22/5, 2018 at 17:45 Comment(0)
M
2

Try the following sample, invoking HTTP GET or POST request in nodejs from AWS lambda

const data = {
    "data": "your data"
};
const options = {
    hostname: 'hostname',
    port: port number,
    path: urlpath,
    method: 'method type'
};
    
const req = https.request(options, (res) => {
    res.setEncoding('utf8');
    res.on('data', (chunk) => {
    // code to execute
});
res.on('end', () => {
    // code to execute      
    });
});
req.on('error', (e) => {
     callback(null, "Error has occured");
});
req.write(data);
req.end();

Consider the sample

Messaline answered 21/11, 2017 at 8:58 Comment(1)
Where is the post body passed in this solution?Dagostino

© 2022 - 2024 — McMap. All rights reserved.