AWS Lambda HTTP POST请求(Node.js)

Mis*_*uti 5 javascript lambda amazon-web-services node.js alexa-skills-kit

我对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 如何在node.js中发出HTTP POST请求?

cod*_*ade 22

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

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}`));
};
Run Code Online (Sandbox Code Playgroud)

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

const http = require('http');
Run Code Online (Sandbox Code Playgroud)


Luc*_*eto 10

我在执行其他答案时遇到困难,因此我发布了对我有用的内容。

在这种情况下,该函数将接收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();

}
Run Code Online (Sandbox Code Playgroud)

通话参数示例

   {
      "url": "example.com",      
       "path": "/apifunction",
       "body": { "data": "your data"}  <-- here your object
    }
Run Code Online (Sandbox Code Playgroud)


小智 2

尝试以下示例,从 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();
Run Code Online (Sandbox Code Playgroud)

考虑样本

  • 该解决方案中的帖子正文在哪里传递? (15认同)