AWS Lambda HTTP POST Request (Node.js)

匿名 (未验证) 提交于 2019-12-03 08:33:39

问题:

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. Any help I'd appreciate it. Sorry for my English. Thank you.

Searches that I found for http post:

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

回答1:

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

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.end(); 

Consider the sample



回答2:

Use HTTP object and use POST as the request type. HTTP requests in AWS Lambda are no different from HTTP requests using NodeJS.

Let me know if you need any more help.



回答3:

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     } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!