AWS Lambda HTTP POST 请求 (Node.js)

AWS Lambda HTTP POST Request (Node.js)

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

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

我为 http post 找到的搜索:

https://www.npmjs.com/package/http-post

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

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

考虑样本

我很难实施其他答案,所以我post正在寻找对我有用的方法。

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

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
    }

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

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