const http = require('http');

exports.handler = function(event, context) {
   var url = event && event.url;
    http.post(url, function(res) {
    context.succeed();
  }).on('error', function(e) {
    context.done(null, 'FAILURE');
  });

};

I am using this in my AWS lambda code to send http request.

I have a JSON file that has to be sent as a part of this post request. How to add JSON ? Where do I specify ?

1 Answers

0
amittn On

If you are asking from where to pickup that json file form, then s3 would be the correct place to put that file and read form the lambda and do a post.

const obj= {'msg': [
{
  "firstName": "test",
  "lastName": "user1"
},
{
  "firstName": "test",
  "lastName": "user2"
}
]};

request.post({
  url: 'your website.com',
  body: obj,
  json: true
}, function(error, response, body){
console.log(body);
});

With just http

const postData = querystring.stringify({
  'msg': 'Hello World!'
});

const options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': Buffer.byteLength(postData)
  }
};

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

// Write data to request body
req.write(postData);
req.end();