Javascript AWS Lambda HTTP POST 请求 (Node.js)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47404325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:50:19  来源:igfitidea点击:

AWS Lambda HTTP POST Request (Node.js)

javascriptnode.jsamazon-web-serviceslambdaalexa-skills-kit

提问by Misuti

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"

我对 AWS lambda 函数和 nodejs 比较陌生。我正在尝试使用来自以下网站的 HTTP POST 请求来尝试获取一个国家/地区的 5 个城市的列表:“ 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.

我一直在寻找如何在 lambda 函数中执行 HTTP POST 请求,但似乎找不到一个很好的解释。

Searches that I found for http post:

我为 http 帖子找到的搜索:

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

https://www.npmjs.com/package/http-post如何在 node.js 中发起 HTTP POST 请求?

采纳答案by Rupali Pemare

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

尝试以下示例,从 AWS lambda 调用 nodejs 中的 HTTP GET 或 POST 请求

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

考虑样本

回答by Luciano Marqueto

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

在这种情况下,函数接收 url、path 和 post 数据

Lambda function

Lambda 函数

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
    }

回答by valdeci

I think that the cleaner and more performatic way, without the needed of externals 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 following Runtimes: Node.js 8.10and Node.js 10.xand is able to do HTTPS requests, to do HTTP requests you need to import and change the object to http:

此 lambda 已在以下运行时制作和测试:Node.js 8.10并且Node.js 10.x能够执行 HTTPS 请求,要执行 HTTP 请求,您需要导入并将对象更改为http

const http = require('http');

回答by Gurdev Singh

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

使用 HTTP 对象并POST用作请求类型。AWS Lambda 中的 HTTP 请求与使用 NodeJS 的 HTTP 请求没有区别。

Let me know if you need any more help.

如果您需要更多帮助,请告诉我。