【问题标题】:AWS Lambda HTTP POST Request (Node.js)AWS Lambda HTTP POST 请求 (Node.js)
【发布时间】:2018-05-04 09:34:25
【问题描述】:

我对 AWS lambda 函数和 nodejs 比较陌生。我正在尝试使用来自该网站的 HTTP POST 请求获取一个国家/地区的 5 个城市的列表:“http://www.webservicex.net/globalweather.asmx?op=GetCitiesByCountry

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

我搜索到的 http 帖子:

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

【问题讨论】:

标签: javascript node.js amazon-web-services aws-lambda alexa-skills-kit


【解决方案1】:

尝试以下示例,从 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();

考虑样本

【讨论】:

  • 这个解决方案中传递的post body在哪里?
【解决方案2】:

我在实施其他答案时遇到了困难,所以我发布了对我有用的答案。

在这种情况下,函数接收 url、路径和发布数据

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

}

调用参数示例

   {
      "url": "example.com",      
       "path": "/apifunction",
       "body": { "data": "your data"}  <-- here your object
    }

【讨论】:

    【解决方案3】:

    我认为不需要外部库的更清洁、更高效的方式可以是这样的:

    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}`));
    };
    

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

    const http = require('http');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      • 2017-02-18
      • 2015-10-27
      • 2021-07-23
      • 2020-09-04
      • 2021-08-16
      • 2017-10-19
      相关资源
      最近更新 更多